Socket.io - Manual reconnect after client-side disconnect
30,615
Solution 1
It works now, with socket.socket.reconnect()
function socket_connect()
{
console.log('func socket_connect');
socket = io.connect('http://url/to/the/app');
}
function socket_reconnect()
{
console.log('func socket_reconnect');
socket.socket.reconnect();
}
function socket_disconnect ()
{
console.log('func socket_disconnect');
if (socket) socket.disconnect();
}
Related: https://github.com/LearnBoost/socket.io-client/issues/251
Solution 2
You can reconnect by following client side config.
// for socket.io version 1.0
io.connect(SERVER_IP,{'forceNew':true });
Solution 3
If you're using Socket.io 1.0, try using the io
manager on the socket to handle manual disconnection and reconnection.
// Connect to socket.io
var socket = io.connect('url');
function manual_disconnect() {
socket.io.disconnect();
}
function manual_reconnect() {
socket.io.reconnect();
}
The reconnecting_attempt, reconnecting, reconnected and connected events on the socket should all be emitted afterwards.
Author by
acc
Updated on June 14, 2020Comments
-
acc almost 4 years
I use
node.js
andsocket.io
to create a real time web application. I will give the users full control of the socket connection, like manual disconnect and (re)connect.function socket_connect() { console.log('func socket_connect'); socket = io.connect('http://url/to/the/app'); } function socket_reconnect() { console.log('func socket_reconnect'); socket_connect(); } function socket_disconnect () { console.log('func socket_disconnect'); if (socket) socket.disconnect(); }
On client start up the
socket_connect()
function works fine, but after usingsocket.disconnect()
, no new connection starts. -
Jörn Berkefeld over 8 yearsirritatingly, socket.disconnect() is still available in 1.x while socket.reconnect() is not. Hence kmftzg's version is probably best
-
Xin over 5 yearswhat about socket.io 2?