Node.js + socket.io: app on server not working cor

2019-09-04 08:01发布

问题:

I'm new to node.js and socket.io and tried to connect the server to the client with the example from http://socket.io/#how-to-use. (no localhost)

Server:

    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 () { });
});

Client:

<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 displays in the console:

Unexpected response code: 502

Also, after receiving every message, Chrome adds

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

to the console. Wheres the problem?

回答1:

The examples from the How-To page all use port 80, which is common for serving websites.

However, you use port 8080 in your example.

Check your web browser's console if it even loads the socket.io script. You may need to provide http://localhost:8080/socket.io/socket.io.js as explicit url and connect with io.connect('http://localhost:8080');

If the above does not work, please share some insight on what port your web server runs on.


There is no code to actually handle any incoming messages server-side in your (updated) example.

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

should at the very least send the message back to the client - your alert is only triggered when the client receives a message. Does the node.js console output any incoming or sent messages? A few lines of my node.js console look like the following upon connecting.

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