Simple scenario:
- Client connects to server with socket.io (
socket = io.connect(...)
)
- Server crashes
- Client tries to reconnect
- User tells client to disconnect (
socket.disconnect()
)
- Server starts
- Client reconnects
It seems that once socket.io starts attempting to reconnect, it cannot be stopped anymore. I want step 4 to prevent step 6 from happening, but it doesn't. What do I have to call instead?
You might want to handle the reconnection yourself.
// Disables the automatic reconnection
var socket = io.connect('http://server.com', {
reconnection: false
});
// Reconnects on disconnection
socket.on('disconnect', function(){
socket.connect(callback);
});
Note: old versions used reconnect
instead of reconnection
.
I think what you need is to configure socket.io
client
to not reconnect
is set property reconnect
to false
I created a little server(server.js
) to test this:
var io = require('socket.io').listen(8888);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Then I created this test.js
to test that it does not reconnect
var client = require('socket.io-client'),
socket = client.connect('http://localhost:8888', {
'reconnect': false
});
socket.on('connect', function () {
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
});
For test.js
to work you will need to install socket.io-client
from npm
issuing npm install socket.io-client
or by adding socket.io-client
(dev-)dependency
to your package.json
.
When I stop server.js
while test.js
is running test.js
will return immediately which I believe is your desired result. When I set reconnect
to true
the client will try to reconnect to server which is not the desired behaviour
In a new socket.io 1.1.x you can do the following:
var manager = io.Manager('http://localhost:9823', { autoConnect: false });
Here is blog link.
Try the following code:
self.socket?.manager?.reconnects = false