Stop socket.io from reconnecting

2019-02-06 13:57发布

Simple scenario:

  1. Client connects to server with socket.io (socket = io.connect(...))
  2. Server crashes
  3. Client tries to reconnect
  4. User tells client to disconnect (socket.disconnect())
  5. Server starts
  6. 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?

标签: socket.io
4条回答
倾城 Initia
2楼-- · 2019-02-06 14:29

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.

查看更多
一纸荒年 Trace。
3楼-- · 2019-02-06 14:38

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.

查看更多
Root(大扎)
4楼-- · 2019-02-06 14:41

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

查看更多
Rolldiameter
5楼-- · 2019-02-06 14:42

Try the following code:

self.socket?.manager?.reconnects = false
查看更多
登录 后发表回答