force client disconnect from server with socket.io

2019-01-07 07:07发布

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?

标签: socket.io
12条回答
啃猪蹄的小仙女
2楼-- · 2019-01-07 07:52

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');
// });
查看更多
狗以群分
3楼-- · 2019-01-07 07:52

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();                      
    });    
查看更多
Anthone
4楼-- · 2019-01-07 07:53

client._onDisconnect() should work

查看更多
你好瞎i
5楼-- · 2019-01-07 07:54

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 ?

查看更多
倾城 Initia
6楼-- · 2019-01-07 07:54

Assuming your socket's named socket, use:

socket.disconnect()
查看更多
够拽才男人
7楼-- · 2019-01-07 07:54

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

client.emit('disconnect') didnt work for me
查看更多
登录 后发表回答