socket.io force disconnect client

11,364

Solution 1

'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();
});

Solution 2

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

socket.close()
Share:
11,364

Related videos on Youtube

Tamas
Author by

Tamas

Full Stack Web Developer turned Technical Instructor, Curriculum Developer, Developer Evangelist and Google Developer Expert in Web Technologies.

Updated on September 14, 2022

Comments

  • Tamas
    Tamas over 1 year

    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");
    });
    
  • nicohvi
    nicohvi over 9 years
    This doesn't call the disconnect event for me.
  • Nikola
    Nikola about 9 years
    Works for me. Thank you!