[javascript] Node.js: socket.io close client connection

How can I close the socket connection on the client side?

I am using:

  • socket.io 0.9
  • node.js 0.10.15
  • express 3.3.4

i.e.: call localhost/test
-- server side

var test = io
.of('/test')
.on('connection', function (socket) {

  console.log('open socket: ' + socket);

  socket.on('disconnect', function () {
    console.log('disconnected event');
    //socket.manager.onClientDisconnect(socket.id); --> endless loop with this disconnect event on server side
    //socket.disconnect(); --> same here
  });
});

-- client side

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

socket.emit('getInitData', function (data) {
  .. do something with data
});

If I load the test-page I need some values from the server (getInitData).
On the first page visit I get the data once, on a reload or second visit I get it twice and so on.

The connection on the server side is beeing closed automatically on page reload and if you leave the page.
But on the client side the connection is still open.
How can I close the connection on the client side or check if there is already a open connection?

UPDATE
I tried now the following: (client side)

window.onbeforeunload = function(e) {
  socket.disconnect();
};

This triggers on the client side the disconnect event, but I still get the twice or tripple response.

This question is related to javascript node.js express socket.io

The answer is


try this to close the connection:

socket.close();

and if you want to open it again:

socket.connect();

I'm trying to close users connection in version 1.0 and found this method:

socket.conn.close()

The difference between this method and disconnect() is that the client will keep trying to reconnect to the server.


For socket.io version 1.4.5:

On server:

socket.on('end', function (){
    socket.disconnect(0);
});

On client:

var io = io();
io.emit('end');

socket.disconnect()

Only reboots the connection firing disconnect event on client side. But gets connected again.

socket.close()

Disconnect the connection from client. The client will keep trying to connect.


Did you try:

socket.disconnect() 

on client?


Just try socket.disconnect(true) on the server side by emitting any event from the client side.


socket.disconnect() is a synonym to socket.close() which disconnect the socket manually.

When you type in client side :

const socket = io('http://localhost');

this will open a connection with autoConnect: true , so the lib will try to reconnect again when you disconnect the socket from server, to disable the autoConnection:

const socket = io('http://localhost', {autoConnect: false});
socket.open();// synonym to socket.connect()

And if you want you can manually reconnect:

socket.on('disconnect', () => {
  socket.open();
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js

Examples related to socket.io

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 WebSockets and Apache proxy : how to configure mod_proxy_wstunnel? node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON] Socket.io + Node.js Cross-Origin Request Blocked Node.js: socket.io close client connection How to send a message to a particular client with socket.io Socket.IO handling disconnect event Get connection status on Socket.io client Which websocket library to use with Node.js? Maximum concurrent Socket.IO connections