Socket.IO socket disconnect event

I can’t handle this disconnect event, I don’t know why the socket doesn’t send it to the client / client, it doesn’t respond!

Server

io.sockets.on('connection', function (socket) { socket.on('NewPlayer', function(data1) { online = online + 1; console.log('Online players : ' + online); console.log('New player connected : ' + data1); Players[data1] = data1; console.log(Players); }); socket.on('DelPlayer', function(data) { delete Players[data]; console.log(Players); console.log('Adios' + data); }); socket.on('disconnect', function () { socket.emit('disconnected'); online = online - 1; }); }); 

Client

  var socket = io.connect('http://localhost'); socket.on('connect', function () { person_name = prompt("Welcome. Please enter your name"); socket.emit('NewPlayer', person_name); socket.on('disconnected', function() { socket.emit('DelPlayer', person_name); }); }); 

As you can see, when the client disconnects the Array object [username], it should be deleted, but it doesn’t

+72
javascript disconnect
Jun 25 '13 at 0:33
source share
4 answers

Well, instead of identifying players by the name of the track with the sockets through which they connected. You may have an implementation of type

Server

 var allClients = []; io.sockets.on('connection', function(socket) { allClients.push(socket); socket.on('disconnect', function() { console.log('Got disconnect!'); var i = allClients.indexOf(socket); allClients.splice(i, 1); }); }); 

Hope this helps you think differently.

+146
Jun 26 '13 at 4:41
source share

For people like @ sha1, I wonder why the OP code is not working -

The OP logic for removing the server-side player is in the DelPlayer event DelPlayer , and the code that emits this event ( DelPlayer ) is inside the disconnected client callback.

The server-side code that emits this disconnected event is inside the disconnected event callback, which fires when the socket loses connection. Since the socket has already lost the connection, the disconnected event does not reach the client.




The decision made executes the logic on the disconnect event on the server side, which is fired when the socket is disconnected, hence it works.

+14
Nov 24 '15 at 11:23
source share

Create a card or set and, using the "on connection" event, set each connected socket for it, otherwise "disconnect it once", remove this socket from the card that we created earlier.

 import * as Server from 'socket.io'; const io = Server(); io.listen(3000); const connections = new Set(); io.on('connection', function (s) { connections.add(s); s.once('disconnect', function () { connections.delete(s); }); }); 
+1
Apr 25 '18 at 0:47
source share

it works for me, hope it works for you

 io.on('connection', function(socket){ console.log('sessionID ' + socket.id + ' connected'); socket.once('disconnect', function () { console.log('sessionID ' + socket.id + ' disconnected'); }); }); 
0
Dec 18 '18 at 5:04
source share



All Articles