Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.IO handling disconnect event

Can't handle this disconnect event, don't know why socket is not sent to the client / client 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 a client disconnects the Array object[person_name] should be deleted, but it's not.

like image 559
Raggaer Avatar asked Jun 25 '13 00:06

Raggaer


People also ask

How do I remove a Socket.IO connection?

click(function(){ socket. disconnect(); }); It disconnects alright.

How do I remove Socket.IO from client side?

var socket = io. connect('http://localhost:3000/test'); socket. on('disconnect', function () { console. log('disconnect client event....'); }); socket.

Does Socket.IO have a timeout?

So, you can configure both the server and client side timeout settings by setting the following timeout properties on the engine.io component inside of socket.io.


1 Answers

Ok, instead of identifying players by name track with sockets through which they have connected. You can have a implementation like

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 will help you to think in another way

like image 167
code-jaff Avatar answered Oct 16 '22 18:10

code-jaff