Srujan Barai Srujan Barai - 4 months ago 7
Node.js Question

What actually the 'socket' object is in How to make sure its usage is optimum?

I currently got a project in which I have to develop a web based board game using

. The thing is, I have jumped directly from Android development to Web dev and so I am facing some issues understanding concepts.

I have already implemented some code where the client connects to the server (
), sends message, receives message etc. I also added a small chat window for players to chat. Its working. I got rough idea about emitting messages and joining room stuffs.

The thing is, I am not sure how to make good use of the
object that server receives when a user connects. Should I save that
object somewhere for future use? Or I just add users to rooms so emitting message to a single user is possible and do not care about saving the socket to a variable? What are the chances that I will need to use the
object again in the future development of this project for doing certain things? I did output the socket object in console to see what information it contained but well, that was too much for me to understand.


In, the socket object is a Javascript object which uses to keep track of the state of a given socket. It has methods and properties on it that are useful for you to use for some purposes and in order to use those, you would have to get a reference to the desired socket object.

But, you do not necessarily need to save the socket object yourself because the server infrastructure saves all of them and keeps them in an organized structure where you can find them at any time in the future if you want to or need to.

It is also common to keep socket references in a closure that allow you to receive messages and respond to the socket that send that message as in this type of scheme:

io.on('connection', function(socket){
    socket.on('getDataX', function(requestArgs) {
        // process the getDataX request

        // send response to that same socket
        socket.emit('replyDataX', ....);

Or, you can broadcast to all sockets with:

io.emit('update', ...);

You can get access to the list of connected sockets stored by in a number of ways. For example:


is an object where the properties are socket ids and the values of the socket objects so one can find a socket object when given an id or can iterate all the connected sockets.

You can also add your own properties to the socket object. Some chat systems will add a username to the socket object so you can also identify or find a given use by their username.