Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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:

This is the content :)

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?

Problem courtesy of: xoxox

Solution

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
Solution courtesy of: mabako

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×