How to avoid create a new socket connection in socket.io after html page refresh? How to avoid create a new socket connection in socket.io after html page refresh? node.js node.js

How to avoid create a new socket connection in socket.io after html page refresh?


You can't block refreshing the page, and there is no way to avoid the socket.io disconnect when a user refreshes the page either.

I would suggest adding a timeout:

  • When a user is seen disconnecting, start a timer, say 10-30 seconds
  • If a user returns to the chat while the timer hasn't finished, don't do anything
  • If a user has not returned after the timer ends, then display the "user has left" message


You can use sessions. Even though the socket disconnects when refreshing occurs, you could still retain some data of that particular user and use that data whenever the socket is connected again.

Here's how you use sessions:

var express = require('express');     var MemoryStore = require('express').session.MemoryStore;app.use(express.cookieParser());app.use(express.session({ secret: "keyboard cat", store: new MemoryStore({ reapInterval: 60000 * 10 })}));app.get('/', function(req,res){    req.session.name ="clients_name";    res.render(__dirname + '/index.jade',{user:req.session.name});});

and you should use jade or any other "View Engine" to get the data passed to the page.