11

I may be doing something wrong here but I can't get my head around this.

The following does not work:

client

$("#disconnectButton").click(function() {
  socket.emit("disconnect");
});

server

socket.on("disconnect", function() {
  console.log("this never gets called");
});

Can't I manually call the disconnect event from the client side? Because the following works:

client

$("#disconnectButton").click(function() {
  socket.emit("whatever");
});

server

socket.on("whatever", function() {
  socket.disconnect();
  console.log("this gets called and disconnects the client");
});
Tamas
  • 10,953
  • 13
  • 47
  • 77
  • What is your reasoning for forcing the disconnect? If you are trying to boot someone for violating limits or security restrictions, you should kill the connection less gracefully. – Brad Dec 20 '13 at 19:45
  • I have a chat app where I'd like to add a 'disconnect' option - so that someone can manually disconnect from the websocket (kind of like replicating if users were to hit refresh.) – Tamas Dec 20 '13 at 19:48

2 Answers2

9

'disconnect' event is Socket.io event,if you use emit to call the 'disconnect',may be cause other problom

so:

$("#disconnectButton").click(function() {
  socket.emit("disconnect");
});

replace:

$("#disconnectButton").click(function() {
  socket.disconnect();
});
Nelson.li
  • 521
  • 4
  • 6
1

For now, socket.emit('disconnect') or socket.disconnect() doesn't work. The correct syntax to disconnect to the socket server is

socket.close()
Anish Sapkota
  • 774
  • 9
  • 19