Socket.IO Session Handling Algorithm

Socket.IO Session Handler for Node.js

Pure JavaScript Module for Session Handling | NPM

Aslam Anver

--

When we use Socket.IO for connecting many clients at a same time with Socket transports we need to handle the connection and disconnection triggers at the time of the event occurred, but unfortunately, you need to do a lot of array-based connection operations to simply handle the connections, that’s why the io-session-handler library was built for.

Let me explain the logic behind this Socket.IO connection method.

When the first time a client connected to Socket.IO server from a browser the Socket.IO creates an ID for the particular connection and manages it by itself and when the user creates another browser tab while the previous connection is still alive, the Socket.IO creates another ID for the user.

Anyhow those two connections belong to a single user which is not understandable by Socket.IO that’s the reason it will consider as two connections are totally two users.

At this problem, we need to find a solution to let the Socket.IO server knows that those two or more connections created from a browser at a particular login session are totally from a single user which cannot be considered as two users but two sessions from a single user.

So what is the solution?

Well, this is actually obvious, when a user login or starts to connect the Socket.IO session we assign a token to the particular user to identify the sessions from user authority. After that how many tabs or browsers the user opens will carry the token to the server until the authentication session time is expired.

Now we know the client-side logic for the solution, furthermore, we can refer to the below table.

Token: 123 | Browser Tab 1 | Username: James
Token: 123 | Browser Tab 2 | Username: James
Token: 123 | Browser Tab 3 | Username: James
Total 3 tabs but a single user.

All the sessions which are created by a single user will be having the same token which will be sent to the Socket.IO server.

Server-side Logic

Now let’s talk about the server-side logic.

The server has an array list of all the users in concurrent connections, as users[]. When a user connects the Socket.IO server at the initial time the server will find the current user’s token on its users[] array list so in this case, now the server will not find any tokens in its array list since this is the first time the particular user tries to connect the server.

Then the server will create an object with token and sessions for the user as below and push the object to the users[] array list.

{
"token":"Token-1",
"connections":[
"I_XzAcQOeIKw8EeMAAAA"
]
}

When the user tries to create another browser tab while the previous tab is still alive, the server will get the ID of the created tab connection and it will push the connection ID to the connections array of the user’s object from users[] array list.

Now the server can understand all the connections coming with the same tokens should be stored as connections of a single user in the users[] array list.

How to handle the disconnect event?

It’s the tricky part of this lesson, we need to think about some facts before implementing programming logic for this part.

When a user connects with the Socker.IO server, as we discussed an object will be created and pushed to the users’ array but let’s assume that if the user refresh the browser tab, Socket.IO will consider as the session is disconnected and once the page refreshed, it will generate another connection ID for the same user.

The user may refresh the page or try to connect the server from an unstable internet connection, in this case, our server should not consider that the user has been totally disconnected rather the server should wait a certain period of time to see whether the user is connecting back or no any responses from the connection after few seconds.

This is how we are gonna implement the disconnect event triggering logic on the Socket.IO server.

Once a client connection is dropped, the server will be still waiting a few seconds for any responses from the client, before it totally removes the user from the users[] array list and triggers the disconnect event.

After a certain period of time is completed but still, the server is not receiving any responses from the client it clearly indicates the user has not refreshed the page or not in an unstable connection but the user has chosen to close the browser or log out which is a good point to trigger the disconnect event and remove the dropped user object from the users[] array list from the server.

Finally, you got a better understanding of this session handling program for Socket.IO,

So are you gonna develop this structure?

Once upon a time, 😃 a developer who was struggling with this issue has built a solution then he tried to help the community as well, that’s where the io-session-handler library was developed for.

You don’t want to write all of this logic while you have this pure JavaScript library in your hand to do the work for you.

A developer who loves the community

Wow, isn’t awesome? that’s me who developed this and I’m gonna explain how to use the session handler library in your projects.

Simple Implementation

This is the basic usage of this concept you can implement in your projects.

This array contains all the concurrent sessions session_handler.sessions

session_handler.sessions

The response will be;

[
{
"token": "5200cc4a59795529",
"connections": [
"I_XzAcQOeIKw8EeMAAAA"
],
"data": {
"lat": 6.836772412061691,
"lon": 79.87546253018081
}
}
]

Disconnect timeout can be changed using the from method options.

const session_handler = require('io-session-handler').from(io, { timeout: 5000 })

Client Connection

You can connect from Web-Client, iOS or Android

HTML / JavaScript

const socket = io({ query: { token: 'client-token' } })

Java

public Socket connect(String token) {
IO.Options opts = new IO.Options();
opts.query = "token=" + token
Socket mSocket = IO.socket("http://127.0.0.1:3000", opts);
mSocket.connect();
return mSocket;
}

Installation

Before installing, download, and install Node.js. Node.js 0.10 or higher is required.

Installation is done using the

$ npm i io-session-handler

Sample Project — Demo

This is a demo project.

The above implementations are enough for basic usage, if you want to implement furthermore, you can refer to the below topics as well.

Advanced Usage | Push & Broadcast Messages

You can send broadcast message to all client sessions at once.

session_handler.broadcastMessage(data)

The push method is capable of sending a push message to only a specific client session and this method returns a boolean value when the session is identified as valid.

let sent = session_handler.pushMessage(client_token, data)

Once the message is delivered to the client, onMessageDelivered method will be triggered with the token of the client and the data it received.

session_handler.onMessageDelivered((data) => {
console.log(data)
})

The data onMessageDelivered contains;

{
"token":"Token-1",
"data":"Some awesome data I received"
}

Client Implementation | Push & Broadcast Messages

Once the client received the push message it should emit to push_message_delivery with the data it receives and the token to let the server understand it’s delivered to a certain client.

{
"token":"client_token",
"data":"Some awesome data I received"
}

The client should on the push_message event to receive push messages from the server

A working example;

Android client library is available at SCM — SCMessaging

Thank you ✌️ I’m Aslam Anver find me on GitHub and StackOverflow as aslamanver & Googlian

io-session-handler is maintained by aslamanver.

--

--

Aslam Anver

Passionate in AI Deep Learning, Find me on GitHub & StackOverflow