Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  163] [ 7]  / answers: 1 / hits: 143194  / 11 Years ago, thu, august 8, 2013, 12:00:00

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.


More From » node.js

 Answers
99

There is no such thing as connection on server side and/or browser side. There is only one connection. If one of the sides closes it, then it is closed (and you cannot push data to a connection that is closed obviously).



Now a browser closes the connection when you leave the page (it does not depend on the library/language/OS you are using on the sever-side). This is at least true for WebSockets (it might not be true for long polling because of keep-alive but hopefuly socket.io handles this correctly).



If a problem like this happens, then I'm pretty sure that there's a bug in your own code (on the server side). Possibly you are stacking some event handlers where you should not.


[#76457] Wednesday, August 7, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
diamondlauryna

Total Points: 386
Total Questions: 93
Total Answers: 103

Location: South Korea
Member since Fri, Sep 11, 2020
4 Years ago
;