Stop socket.io from reconnecting

后端 未结 6 707
情歌与酒
情歌与酒 2020-12-31 05:58

Simple scenario:

  1. Client connects to server with socket.io (socket = io.connect(...))
  2. Server crashes
  3. Client tries to reconnect
相关标签:
6条回答
  • 2020-12-31 06:29

    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

    0 讨论(0)
  • 2020-12-31 06:33

    Try the following code:

    self.socket?.manager?.reconnects = false
    
    0 讨论(0)
  • 2020-12-31 06:34

    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.

    0 讨论(0)
  • 2020-12-31 06:35

    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.

    0 讨论(0)
  • 2020-12-31 06:42

    you can just call socket.disconnect(), then it will stop trying to reconnect.

    0 讨论(0)
  • 2020-12-31 06:51

    This one works great for me, though , it shoots one more attempt before stops completely.

    socket.io-client": "2.2.0"

    this.socket.io.reconnectionAttempts(0);

    0 讨论(0)
提交回复
热议问题