136

Is there any way to disconnect a client with SocketIO, and literally close the connection? So if someone is connected to my server, and I want to close the connection between them and my server, how would I go about doing that?

Oliver Salzburg
  • 21,652
  • 20
  • 93
  • 138
Daniel Kenney
  • 1,493
  • 2
  • 10
  • 10

18 Answers18

166

Edit: This is now possible

You can now simply call socket.disconnect() on the server side.

My original answer:

This is not possible yet.

If you need it as well, vote/comment on this issue.

nh2
  • 24,526
  • 11
  • 79
  • 128
  • So I'm doing that, and it does force the client to disconnect, unfortunately it appears that the client simply reconnects immediately. Am I misunderstanding what is going on, or is that the expected behaviour? – kybernetikos Jan 21 '13 at 08:39
  • @kybernetikos Yes, I would expect this - the client can choose what to do with their own after all. Often, you want to kick the other side from the *current* connection, say because of an auth timeout - a reconnect after this would probably even be desireable. – nh2 Jan 21 '13 at 16:13
  • So do you know of any way of telling the client 'go away and I really mean it'? I'm thinking from the point of view of determining that a client is behaving badly and not wanting them using up resource on my server. – kybernetikos Jan 21 '13 at 17:09
  • @kybernetikos No, you can't do that (generally). If you are programming the client side though, you can of course implement any logic you want, e.g. stop it from reconnecting. If not, have to repeatedly kick the users, or if really necessary, resort to standard blocking techniques; the lower level these are implemented (e.g. `iptables`), the more resources you will save. In most cases, simply kicking the client should be sufficient though, since socketio does not connect that rapidly, and if somebody really wants to DoS you, they have other ways anyway (e.g. downloading pages from you). – nh2 Apr 17 '13 at 14:44
  • hi @nh2, I have also want to disconnect socket from node.js (server side), but problem is How do I get socket from IO.Sockets of my particular/specific user? Or I have to store this socket in some variable or array? – Manish Sapkal Apr 15 '14 at 06:55
  • @ManishSapkal If your "user" is some arbitrary object you define in your application, then sure, you have to store what socket(s) belong to a user the first time you associate them. – nh2 Apr 15 '14 at 12:13
  • thanks @nh2 for reply. Now I am facing very strange problem. I have written following code on server side. io.sockets.on('connection', function(socket) { console.log('A socket with sessionID connected! ' + socket.id); socket.on('disconnect', function() { console.log('socket.on.disconnect '); }); socket.on('error', function(err) { }); socket.on('message', function(data) { }); }); With above code my 'disconnected' event fire after 'connect' event? I don't know where is the mistek I have done. do you get any clue? – Manish Sapkal Apr 15 '14 at 12:55
  • 1
    @ManishSapkal You should probably open a new question for that, it does not fit well into comments. – nh2 Apr 16 '14 at 14:16
  • does this have a callback function or does it syncronously disconnect? I cannot find anything in socket.io docs... – notgiorgi Oct 10 '16 at 08:28
  • @nh2 can you add a basic snippet demonstrating how to call socket.disconnect()? Can we call it in a socket message event listener? – Akshay Kumar Feb 20 '21 at 15:52
  • 1
    @Akshay 10 years later, I am no longer using socket.io; best asked in their forums or issue tracker. – nh2 Mar 07 '21 at 21:59
19

socket.disconnect() can be used only on the client side, not on the server side.

Client.emit('disconnect') triggers the disconnection event on the server, but does not effectively disconnect the client. The client is not aware of the disconnection.

So the question remain : how to force a client to disconnect from server side ?

Fabien
  • 263
  • 1
  • 2
  • 2
    You don't have to call `Client.emit('disconnect')` manually anymore with recent socket.io versions, there is now a server-side `socket.disconnect()` (see my answer). – nh2 Jun 16 '12 at 03:12
  • I agree, this answer is no longer valid, because now the `socket.disconnect()` can be used at the server side too. – Vassilis Barzokas Apr 13 '16 at 07:54
  • @VassilisBarzokas What if I want a callback and pass some parameters to the callback after the `disconnect()` function is finished? – newguy Jan 13 '17 at 10:28
  • create a agreed set of messages where one party informs the other party that they wish to disconnect, then do what you need to do, and _then_ actually disconnect. – Mike 'Pomax' Kamermans Jun 16 '19 at 16:12
12

Any reason why you can't have the server emit a message to the client that makes it call the disconnect function?

On client:

socket.emit('forceDisconnect');

On Server:

socket.on('forceDisconnect', function(){
    socket.disconnect();
});
system64
  • 909
  • 1
  • 11
  • 27
quahada
  • 131
  • 1
  • 2
11

Checking this morning it appears it is now:

socket.close()

https://socket.io/docs/client-api/#socket-close

HAS-Jack
  • 620
  • 6
  • 10
5

For those who found this on google - there is a solution for this right now:

Socket.disconnect() kicks the client (server-side). No chance for the client to stay connected :)

Sascha Gehlich
  • 1,007
  • 8
  • 12
  • 2
    How Do I find socket of user who is disconnected on server? – Manish Sapkal Apr 15 '14 at 07:35
  • Manish: Listen for the socket's `disconnect` event to find out whether it has disconnected. Can also be the `close` event, I'm not quite sure. See socket.io's documentation for further information on this. – Sascha Gehlich Jun 10 '14 at 17:38
5

This didn't work for me:

`socket.disconnect()` 

This did work for me:

socket.disconnect(true)

Handing over true will close the underlaying connection to the client and not just the namespace the client is connected to Socket IO Documentation.


An example use case: Client did connect to web socket server with invalid access token (access token handed over to web socket server with connection params). Web socket server notifies the client that it is going to close the connection, because of his invalid access token:

// (1) the server code emits
socket.emit('invalidAccessToken', function(data) {
    console.log(data);       // (4) server receives 'invalidAccessTokenEmitReceived' from client
    socket.disconnect(true); // (5) force disconnect client 
});

// (2) the client code listens to event
// client.on('invalidAccessToken', (name, fn) => { 
//     // (3) the client ack emits to server
//     fn('invalidAccessTokenEmitReceived');
// });
Baran
  • 2,710
  • 1
  • 23
  • 23
4

Assuming your socket's named socket, use:

socket.disconnect()
Erik
  • 88,732
  • 13
  • 198
  • 189
3

In my case I wanted to tear down the underlying connection in which case I had to call socket.disconnect(true) as you can see is needed from the source here

Duncan
  • 858
  • 1
  • 11
  • 29
2

I'm using client.emit('disconnect') + client.removeAllListeners() for connected client for ignore all events after disconnect

T J
  • 42,762
  • 13
  • 83
  • 138
skyman
  • 229
  • 1
  • 13
2

client._onDisconnect() should work

T J
  • 42,762
  • 13
  • 83
  • 138
Emmerman
  • 2,371
  • 15
  • 9
  • 1
    This works perfectly.. Im maintain my own mapping to clients.. using that mapping ... easily disconnecting clients.. cheers – Arenstar Mar 29 '11 at 15:20
1

Socket.io uses the EventEmitter pattern to disconnect/connect/check heartbeats so you could do. Client.emit('disconnect');

T J
  • 42,762
  • 13
  • 83
  • 138
1

To disconnect socket forcefully from server side

socket.disconnect(true)

OR

To disconnect socket by client side event

On client:

socket.emit('forceDisconnect');

On Server:

socket.on('forceDisconnect', function(){
    socket.disconnect(true);
});
GAURAV MOKASHI
  • 1,906
  • 2
  • 14
  • 17
0

I am using on the client side socket.disconnect();

client.emit('disconnect') didnt work for me
yonia
  • 1,681
  • 1
  • 14
  • 12
0

You can do socket = undefined in erase which socket you have connected. So when want to connected do socket(url)

So it will look like this

const socketClient = require('socket.io-client');

let socket;

// Connect to server
socket = socketClient(url)

// When want to disconnect
socket = undefined;
0

I have using the socket client on React Native app, when I called socketIOClient.disconnect() this disconnects from the server but when I connect to the socket again the previous events were connected again, and the below code works for me by removing all existing events and disconnecting socket conneciton.

socketIOClient.removeAllListeners();
socketIOClient.disconnect(true);
U.A
  • 2,991
  • 3
  • 24
  • 36
0

You can call socket.disconnect() on both the client and server.

Coder Gautam YT
  • 1,044
  • 7
  • 20
-2

Add new socket connections to an array and then when you want to close all - loop through them and disconnect. (server side)

var socketlist = [];

   io.sockets.on('connection', function (socket) {
        socketlist.push(socket);  
        //...other code for connection here..
   });


    //close remote sockets
    socketlist.forEach(function(socket) {        
        socket.disconnect();                      
    });    
PodTech.io
  • 4,874
  • 41
  • 24
-2

use :

socket.Disconnect() //ok

do not use :

socket.disconnect()

m-tech
  • 338
  • 2
  • 14