【问题标题】:Node.js + socket.io: app on server not working correctlyNode.js + socket.io:服务器上的应用程序无法正常工作
【发布时间】:2012-11-04 19:50:13
【问题描述】:

我是 node.js 和 socket.io 的新手,并尝试使用来自 http://socket.io/#how-to-use 的示例将服务器连接到客户端。 (没有本地主机)

服务器:

    var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(80);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html'+err);
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
    socket.on('message', function(msg){
        console.log('Got text: '+msg);
        socket.broadcast.send(msg);
    });
    socket.on('disconnect', function () { });
});

客户:

<html><head><script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect();
  socket.on('connect', function () {
    alert('connected.');

    socket.on('message', function (msg) {
      // my msg
      alert('message received: '+msg);
    });
    socket.send('hi');

  });


</script>
</head><body>This is the content :)</body>
</html>

Google Chrome 显示在控制台中:

Unexpected response code: 502

另外,Chrome 在收到每条消息后都会添加

GET http://[myServer]/socket.io/1/?t=1352313105809  socket.io.js:1659
Socket.handshake socket.io.js:1659
Socket.connect socket.io.js:1699
maybeReconnect

到控制台。 问题出在哪里?

【问题讨论】:

    标签: javascript node.js websocket socket.io


    【解决方案1】:

    How-To 页面中的示例都使用端口 80,这对于服务网站很常见。

    但是,您在示例中使用端口 8080。

    检查您的网络浏览器的控制台是否加载了 socket.io 脚本。 您可能需要提供http://localhost:8080/socket.io/socket.io.js 作为显式网址并与io.connect('http://localhost:8080'); 连接

    如果上述方法不起作用,请分享您的网络服务器运行在哪个端口上的一些见解。


    在您的(更新的)示例中,没有任何代码可以在服务器端实际处理任何传入消息。

    `socket.on('message', function(msg){
      console.log('Got text: '+msg);
      socket.send(msg);
    });
    

    至少应该将消息发送回客户端 - 您的警报仅在客户端收到消息时触发。 node.js 控制台是否输出任何传入或发送的消息?连接后,我的 node.js 控制台的几行如下所示。

    debug - client authorized
    info  - handshake authorized ...
    debug - setting request GET /socket.io/1/...
    debug - set heartbeat interval for client ...
    debug - client authorized for
    debug - websocket writing 1::
    debug - sending data ack packet
    

    【讨论】:

    • 谢谢。我编辑了代码并且它确实连接了,所以我认为脚本(socket.io.js)已加载。但是没有收到任何消息。你有什么建议我可以测试一条消息是否真的发送了吗?
    • 谢谢,它终于收到了自己的消息,但没有收到其他消息(当我连接到不同的浏览器时)。 Opera 不会在控制台中打印任何内容。谷歌浏览器打印“意外响应代码:502”,但它仍然有效。 (我编辑了我的问题并添加了一些信息)
    • socket.broadcast.send 会将消息发送给除发送它的用户之外的所有用户。
    • 谢谢!不知何故,它现在可以工作了,但这只是因为 'socket.broadcast.send' 方法:)
    猜你喜欢
    • 2012-01-20
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 2011-05-17
    • 1970-01-01
    相关资源
    最近更新 更多