force client disconnect from server with socket.io and nodejs
Asked Answered
G

17

138

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?

Guzel answered 19/2, 2011 at 1:24 Comment(0)
M
167

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.

Met answered 6/4, 2011 at 0:29 Comment(11)
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?Anuska
@Anuska 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.Met
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.Anuska
@Anuska 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).Met
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?Natoshanatron
@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.Met
thanks @Met 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?Natoshanatron
@ManishSapkal You should probably open a new question for that, it does not fit well into comments.Met
does this have a callback function or does it syncronously disconnect? I cannot find anything in socket.io docs...Gumwood
@Met can you add a basic snippet demonstrating how to call socket.disconnect()? Can we call it in a socket message event listener?Dail
@Akshay 10 years later, I am no longer using socket.io; best asked in their forums or issue tracker.Met
E
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 ?

Estancia answered 16/3, 2011 at 10:45 Comment(4)
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).Met
I agree, this answer is no longer valid, because now the socket.disconnect() can be used at the server side too.Polled
@VassilisBarzokas What if I want a callback and pass some parameters to the callback after the disconnect() function is finished?Coryza
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.Unpolite
I
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();
});
Ilmenite answered 29/3, 2012 at 6:18 Comment(1)
Because client-side code can never be relied upon to function exactly as you want. Users can easily modify it.Censurable
O
12

Checking this morning it appears it is now:

socket.close()

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

Octamerous answered 25/5, 2019 at 15:3 Comment(2)
no more valid, any new update ?Dubois
@KoLynn it's valid I've just tried and it works. at least for v4. socket.io/docs/v4/client-api/#socketcloseNowak
I
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 :)

Inbound answered 7/4, 2012 at 11:46 Comment(2)
How Do I find socket of user who is disconnected on server?Natoshanatron
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.Inbound
S
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');
// });
Steadman answered 12/4, 2018 at 18:39 Comment(0)
M
4

Assuming your socket's named socket, use:

socket.disconnect()
Meathead answered 19/2, 2011 at 1:52 Comment(1)
Unfortunately, this doesn't work. I'm trying to close the connection to a specific client from the server-side.Guzel
E
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

Engenia answered 19/5, 2015 at 2:6 Comment(0)
U
2

client._onDisconnect() should work

Underclothing answered 29/3, 2011 at 9:49 Comment(1)
This works perfectly.. Im maintain my own mapping to clients.. using that mapping ... easily disconnecting clients.. cheersBarbrabarbuda
V
2

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

Verulamium answered 7/6, 2012 at 6:29 Comment(0)
T
2

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);
});
Teleprinter answered 8/7, 2021 at 20:49 Comment(0)
L
1

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

Landers answered 11/3, 2011 at 0:46 Comment(0)
G
0

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

client.emit('disconnect') didnt work for me
Gelatinous answered 27/3, 2016 at 9:16 Comment(0)
F
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;
Ferrell answered 2/11, 2019 at 6:29 Comment(0)
M
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);
Meed answered 19/6, 2021 at 5:5 Comment(0)
C
-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();                      
    });    
Checkerbloom answered 28/3, 2017 at 17:52 Comment(0)
N
-2

use :

socket.Disconnect() //ok

do not use :

socket.disconnect()

Noria answered 30/1, 2019 at 21:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.