Alexander Mills
Alexander Mills

Reputation: 100506

socket.io listen / listening event

I am surprised looking at the socket.io docs that there is no event that is fired by socket.io when it is bound to a port...I am looking for a "listen" / "listening" event...

http://socket.io/docs/server-api/

I have this simple module that is initialized with a http.Server instance:

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

var socketServer = null;

function getSocketServer(httpServer) {

    if (socketServer === null) {

        if (httpServer == null) {
            throw new Error('need to init socketServer with http.Server instance');
        }

        socketServer = io.listen(httpServer);
    }

    return socketServer;

}


module.exports = {
    getSocketServer:getSocketServer
};

when I require this module, I want to listen for a 'listening' event.

Something like:

var socket = require('./socket-cnx').getSocketServer();

socket.on('listening',function(err){

});

I suppose the primary reason is because the on API is used for event names.

Upvotes: 1

Views: 11402

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146164

So socket.io itself doesn't listen. The http server listens, and that's the object that will emit the listening event.

If you allow socket.io to create the http server instance for you, that instance is published as the httpServer property of your io instance so you should be able to do io.httpServer.on('listening', myOnListeningHandler)

Here's a working sample program:

var io = require('socket.io')(4001)

io.httpServer.on('listening', function () {
  console.log('listening on port', io.httpServer.address().port)
})

Upvotes: 6

Related Questions