I couldnt send the data from the client to server on disconnect event
//clients side
var gname = "asd";
socket.emit('disconnect',gname);
//server side
socket.on('disconnect', function (data) {
console.log(data);
var i = connect_clients.indexOf(data);
if(i != -1) {
connect_clients.splice(i, 1);
}
}
You won't be able to, because the socket was disconnected from server. The event on server fires when the server detects disconnect (not magically by a fraction before that) and the "bridge" between client and server is already closed/interrupted/whatever - no connectivity means no data interchange.
You have two options on how to do something with disconnected client:
use database or local variables to store some user information by 'socket.id' (for example track down online users). When you get disconnect
event on server you can see socket's id what get disconnected. Use this id
to do needed stuff like decrease online users count and broadcast this to others.
(rather bad solution) wait for reconnect
event on client and send the data from there when the connection will be reestablished. Of course if the server will remains down the data probably will be lost.
If you need to perform some simple server side stuff, solution 1 may work just fine, but if you have something complex, like unsaved form data, you will have to come up with some sort of saving the data in localStorage
, for example, and sync it back upon reconnect
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With