【问题标题】:Node.js and socket.io : Can not communicate server/client via WebsocketNode.js 和 socket.io:无法通过 Websocket 通信服务器/客户端
【发布时间】:2014-05-13 10:44:06
【问题描述】:

我是 node.js/socket.io/websocket 的新手,我正在尝试创建一个网络聊天应用程序。目前我被困在一个问题上好几天了:无论我多么努力,我都无法通过 websocket 进行浏览器/服务器通信。

我的服务器代码:

    var express = require("express");
    var app = express();
    var port = 3700;

    var io = require('socket.io').listen(app.listen(port));

    console.log("Listening on port " + port);

    io.sockets.on('connection', function (socket) {
        console.log("connect");
            socket.emit('globalmessage', { message: 'welcome to the chat !' });

            socket.on('send', function (data) {
        io.sockets.emit('message', data);
            });
    });

我的客户代码:

        var messages = [];
        var socket = io.connect('http://localhost:3700');
        var field = document.getElementById("field");
        var sendButton = document.getElementById("send");
        var content = document.getElementById("content");

        var name = 'test';
        var role = 1;

        socket.on('message', function (data) {
            if(data.message) {
                    messages.push(data);
                    var html = '';

                    for(var i=0; i<messages.length; i++) {
                            html += messages[i].message + '<br />';
                    }
                    content.innerHTML = html;
            } else {
                    console.log("There is a problem:", data);
            }
        });

        socket.on('globalmessage', function (data) {
            content.innerHTML += data.message;
        });     

        sendButton.onclick = function() {
            var text = field.value;
            socket.emit('send', { message: text, username: name, role: userrole});
        };

当我启动节点 js 服务器并通过浏览器(chrome 和 firefox)访问客户端时,我在 cmd windows 中获得了这些数据:

    info  - socket.io started
    Listening on port 3700
    debug - served static content /socket.io.js
    debug - client authorized
    info  - handshake authorized 7492ni4I5TCkRNvfG8WU
    debug - setting request GET /socket.io/1/websocket/7492ni4I5TC
    debug - set heartbeat interval for client 7492ni4I5TCkRNvfG8WU
    debug - client authorized for
    debug - websocket writing 1::
    connect
    debug - websocket writing 5:::{"name":"globalmessage","args":[
    come to the chat !"}]}
    debug - emitting heartbeat for client 7492ni4I5TCkRNvfG8WU
    debug - websocket writing 2::
    debug - set heartbeat timeout for client 7492ni4I5TCkRNvfG8WU

如你所见,有 websocket 写 5:::{"name":"globalmessage","args":[ Welcome to the chat !"}]} 这意味着当客户端连接时服务器可以读取,并且确实将消息发送回客户端,但在客户端没有任何反应,我无法读取消息,事件根本没有触发。当我尝试从客户端向服务器发送消息时也没有任何反应。

在萤火虫控制台我看到有 1 个成功请求来解决

localhost:3700/socket.io/1/?t=1399976614584

响应 7492ni4I5TCkRNvfG8WU:60:60:websocket

如果我将传输从 websocket 更改为 xhr-polling 一切正常,客户端可以接收服务器消息,可以将消息发送回服务器,所以我认为代码很好(实际上我从 http://code.tutsplus.com/tutorials/real-time-chat-with-nodejs-socketio-and-expressjs--net-31708 复制了代码) .

那么你能帮我解决我当地的 websocket 设置有什么问题吗?我不知道出了什么问题,因为 ajax 轮询一切正常,我真的需要它来使用 websocket。我所有的测试都是在我的本地完成的:windows 7 home premium,xampp 3.1.0(即使我关闭了 apache,websocket 也无法工作)

谢谢大家!

【问题讨论】:

  • 那么,当您单击sendButton 时,什么都没有发生?我建议在按钮的onclick 处理程序和socket.on('message' 处理程序中放置一些console.logs。

标签: node.js sockets websocket


【解决方案1】:

我之前在一个项目中使用过带有 express 的 socket io,但我从来没有遇到过这个问题。我可以与您分享我拥有的代码

var io = require('socket.io');
var io_connection = io.listen(server, {
origins: '*:*',
log: true,
'heartbeat timeout': 6000,
'close timeout': 6000,
'log level': 3,
'transports': [
  'websocket',
  'flashsocket',
  'htmlfile',
  'xhr-polling',
  'jsonp-polling'
]
});

io_connection
.on('connection', function(socket) {
  user(socket); // bind user socket connection
  poll(socket); // bind user's socket to poll related sockets

 });

return io;

希望对你有帮助

【讨论】:

  • 感谢您的回复,我尝试了您的代码,但仍然无法正常工作,这次服务器也没有向客户端发送消息。我使用 socket.emit('globalmessage', { message: 'welcome to the chat !' }); on .on('connection 而不是 user(socket) 和 poll(socket) (我猜它们是你的函数?)
  • 对不起,您需要取出用户(套接字),这是我用来将这些套接字绑定到其各自侦听器的另一个文件。您是否尝试将侦听器放入 on('connection') 中?
  • 嗨,尤金,我猜 user(socket) 是你的函数,所以我确实把它拿出来了,但它仍然对我不起作用。我现在正在尝试在 heroku 上托管我的应用程序,看看我是否可以通过那里的 websocket 使其工作。
  • 对不起@Mir,这对我来说很奇怪。好的,一切顺利:D
猜你喜欢
  • 1970-01-01
  • 2021-09-29
  • 2019-03-05
  • 1970-01-01
  • 2011-04-28
  • 2011-08-18
  • 2018-01-03
  • 2021-11-18
  • 1970-01-01
相关资源
最近更新 更多