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

qichunren picture qichunren · Mar 2, 2012 · Viewed 14.9k times · Source

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

Answer

Jani Hartikainen picture Jani Hartikainen · Mar 2, 2012

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