Socket.IO Session Handling Algorithm

Socket.IO Session Handler for Node.js

Pure JavaScript Module for Session Handling | NPM

Image for post
Image for post

So what is the solution?

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.

Server-side Logic

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

How to handle the disconnect event?

Image for post
Image for post
A developer who loves the community
Image for post
Image for post

Simple Implementation

session_handler.sessions
[
{
"token": "5200cc4a59795529",
"connections": [
"I_XzAcQOeIKw8EeMAAAA"
],
"data": {
"lat": 6.836772412061691,
"lon": 79.87546253018081
}
}
]
const session_handler = require('io-session-handler').from(io, { timeout: 5000 })

Client Connection

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

$ npm i io-session-handler

Sample Project — Demo

Advanced Usage | Push & Broadcast Messages

session_handler.broadcastMessage(data)
let sent = session_handler.pushMessage(client_token, data)
session_handler.onMessageDelivered((data) => {
console.log(data)
})
{
"token":"Token-1",
"data":"Some awesome data I received"
}

Client Implementation | Push & Broadcast Messages

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

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store