Node.js + socket.io:服务器上的app无法正常工作

时间:2012-11-04 19:50:13

标签: javascript node.js websocket socket.io

我是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

到控制台。 那问题呢?

1 个答案:

答案 0 :(得分:3)

“操作方法”页面中的示例全部使用端口80,这对于服务网站很常见。

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

如果它甚至加载了socket.io脚本,请检查您的Web浏览器的控制台。 您可能需要提供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