53

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.

baam
  • 1,122
  • 2
  • 14
  • 25
  • How do you handle `getInitData` event? – Setthase Aug 08 '13 at 13:17
  • `getInitData` returns some values from my own written node addon. those values are beeing set in a form (checkbox, textfield, etc.) but i just found out that the connection on the server is started multiple times. Every time i reload the page a new connection is added even though the connection is beeing closed. – baam Aug 08 '13 at 13:26
  • 1
    There is no such thing as connection on server side and 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 you are using), this is at least true for WebSockets. 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. – freakish Aug 08 '13 at 13:26
  • You are probably right, freakish. Is there a possibility to clean/delete handlers after a disconnect? In the main post you can see that I add every time I reload the page a new handler to the `io`. – baam Aug 08 '13 at 13:55
  • Yep, you were right. I needed to add the handler for the specific namespace not in the 'route' where it gets calles multiple times. a cleanup solution would be nice for this. Now I have the whole code in my app.js. It works but it looks ugly. – baam Aug 08 '13 at 14:08
  • 1
    @baam Yes, that's one of the most common issues. I've posted my comment as an answer so you can accept it. :) – freakish Aug 09 '13 at 12:58

8 Answers8

85

Did you try:

socket.disconnect() 

on client?

Milan Babuškov
  • 59,775
  • 49
  • 126
  • 179
  • Nope, I didnt. I thought that would just trigger the disconnect event on the server side? And when would I trigger this? – baam Aug 08 '13 at 13:00
  • I miss that in your question, but when DO you want to close the connection on client? – Milan Babuškov Aug 08 '13 at 13:01
  • Every time the server connection is beeing closed. (reload/refresh and page unload/leave) – baam Aug 08 '13 at 13:03
  • 2
    I updated the main post. The `socket.disconnect()` on the client side does trigger the disconnect event but it does not solve my problem :/ – baam Aug 08 '13 at 13:12
  • does socket.disconnect() trigers the disconnect event in that same line? for example: if the next line is" console.log('i am after dc'). will that line be executed before the disconnect event, or after? Thanks! @MilanBabuškov – chelo_c Jan 13 '16 at 06:43
  • You should mention the parameter; if it's `true`, the underlying connection will be closed as well, but otherwise it's left open (presumably to speed up reconnection) – Nic Jun 02 '18 at 05:34
24

For socket.io version 1.4.5:

On server:

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

On client:

var socket = io();
socket.emit('end');
Supun Praneeth
  • 3,087
  • 2
  • 30
  • 33
Himani Agrawal
  • 1,242
  • 12
  • 14
13

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.

freakish
  • 54,167
  • 9
  • 132
  • 169
  • 13
    *"If one of the sides closes it, then it is closed"* - how to close it programatically from each side..? I couldn't find any documentation – T J Nov 17 '15 at 19:36
  • Actually,when u leave the page or direct to another page with the link, the connection of your `websocket` will automatically close and it is because the worker to support the page has been abort. Make a try on _shared worker_ ,in which u can initialize your connection on it and persist the socket object . – Chopping Mar 05 '19 at 05:31
7
socket.disconnect()

Only reboots the connection firing disconnect event on client side. But gets connected again.

socket.close()

Disconnect the connection from client. The client will keep trying to connect.

Shapeshifter
  • 510
  • 6
  • 11
Ali Azhar
  • 1,703
  • 19
  • 14
5

socket.disconnect() is a synonym to socket.close() which disconnect the socket manually.

When you type in client side :

const socket = io('http://localhost');

this will open a connection with autoConnect: true , so the lib will try to reconnect again when you disconnect the socket from server, to disable the autoConnection:

const socket = io('http://localhost', {autoConnect: false});
socket.open();// synonym to socket.connect()

And if you want you can manually reconnect:

socket.on('disconnect', () => {
  socket.open();
});
Ahmad Zahabi
  • 1,110
  • 12
  • 15
2

I'm trying to close users connection in version 1.0 and found this method:

socket.conn.close()

The difference between this method and disconnect() is that the client will keep trying to reconnect to the server.

JakubKnejzlik
  • 6,363
  • 3
  • 40
  • 41
1

try this to close the connection:

socket.close();

and if you want to open it again:

socket.connect();
0

Just try socket.disconnect(true) on the server side by emitting any event from the client side.

Lalit Kumar Maurya
  • 5,475
  • 2
  • 35
  • 29