20

I have tried socket.io, I found when client html page load, a new socket connection created.When I refresh the page, I found a new socket connection create, and then the old connection disconnect.

My problem is how to avoid this? Because I am building a chat room application. When a user enter the room page, on "connection" servier side emit "Welcome user xxx come!", and on 'disconnec' event emit "User xxx leaved." But when a user refresh the current page, this will fire 'disconnect' event and filre 'connected' event again. And it will emit "Welcome user xxx come!" and "User xxx leaved." messages together.

How to ignore page refresh event?And Just like http session?


Update: I have already found way to solve the problem. from this question Handle browser reload socket.io

Community
  • 1
  • 1
qichunren
  • 4,405
  • 7
  • 37
  • 48
  • Found a possible solution here : https://stackoverflow.com/questions/41924713/node-js-socket-io-page-refresh-multiple-connections – Abbin Varghese Jan 02 '19 at 10:22

2 Answers2

22

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
Jani Hartikainen
  • 42,745
  • 10
  • 68
  • 86
9

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.

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
Jude Calimbas
  • 2,764
  • 2
  • 27
  • 24