Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: socket.io close client connection

How can I close the socket connection on the client side?

I am using:

  • socket.io 0.9
  • node.js 0.10.15
  • express 3.3.4

i.e.: call localhost/test
-- server side

var test = io .of('/test') .on('connection', function (socket) {    console.log('open socket: ' + socket);    socket.on('disconnect', function () {     console.log('disconnected event');     //socket.manager.onClientDisconnect(socket.id); --> endless loop with this disconnect event on server side     //socket.disconnect(); --> same here   }); }); 

-- client side

var socket = io.connect('http://localhost:3000/test'); socket.on('disconnect', function () {    console.log('disconnect client event....'); });  socket.emit('getInitData', function (data) {   .. do something with data }); 

If I load the test-page I need some values from the server (getInitData).
On the first page visit I get the data once, on a reload or second visit I get it twice and so on.

The connection on the server side is beeing closed automatically on page reload and if you leave the page.
But on the client side the connection is still open.
How can I close the connection on the client side or check if there is already a open connection?

UPDATE
I tried now the following: (client side)

window.onbeforeunload = function(e) {   socket.disconnect(); }; 

This triggers on the client side the disconnect event, but I still get the twice or tripple response.

like image 992
baam Avatar asked Aug 08 '13 12:08

baam


People also ask

How do you check if socket IO client is connected or not?

You can check the socket. connected property: var socket = io. connect(); console.

How do I secure a Socket.IO connection?

All you have to do is updating the remote session store on node server when a new login/logout happens in your php server. Show activity on this post. The excellent passport framework for express uses secure cookies to validate identity. There is even a module to access it from socket.io.


2 Answers

Did you try:

socket.disconnect()  

on client?

like image 153
Milan Babuškov Avatar answered Sep 18 '22 12:09

Milan Babuškov


For socket.io version 1.4.5:

On server:

socket.on('end', function (){     socket.disconnect(0); }); 

On client:

var socket = io(); socket.emit('end'); 
like image 43
Himani Agrawal Avatar answered Sep 22 '22 12:09

Himani Agrawal