Gavin
Gavin

Reputation: 7976

Socket.io creating multiple connections

I'm integrating socket.io into my project. I'm using the code below and it's creating 6 connections after the first request. Is this normal?

server.listen(
    port,
    function()
    {
        console.log('Node.js server listening on port ' + port);
    }
);

server.on(
    'connection',
    function(socket)
    {
        console.log('socket.io connection');
    }
);

And here is the console.log output:

Node.js server listening on port 3000
socket.io connection
socket.io connection
socket.io connection
socket.io connection
socket.io connection
socket.io connection

Upvotes: 1

Views: 3622

Answers (1)

Oleg
Oleg

Reputation: 23307

You get this result because (as far as I understand) your server object is an instance of node's http.Server class, and is not connected with Socket.IO at all. In your example, 'connection' event is being fired on any request the your node server. It looks like browser sends 6 requests to your node server: page, favicon.ico, and 4 other requests (it might be images, javascripts, css, etc.).

To integrate socket.io into your project you may use the following code:

var http = require('http');
var sio = require('socket.io');

var server = http.createServer(function(req, res) {
    //you request handler here
});

var io = sio(server);

io.on('connection', function(socket) {
    console.log('socket connected');
    //now you can emit and listen messages
});

var port = 3000;
server.listen(port, function() {
    console.log('Node.js server listening on port ' + port);
});

And, of course, the official documentation might be very helpful. Good luck :)

Upvotes: 2

Related Questions