Socket IO reconnect?

前端 未结 5 1647
终归单人心
终归单人心 2020-12-12 19:06

How to reconnect to socket io once disconnect has been called?

Here\'s the code

function initSocket(__bool){                    
    if(         


        
5条回答
  •  旧巷少年郎
    2020-12-12 20:05

    I had an issue with socket-io reconnect. May be this case will help someone. I had code like this:

    var io = require('socket.io').listen(8080);
    DB.connect(function () {
        io.sockets.on('connection', function (socket) {
            initSockets(socket);
        });
    });
    

    this is wrong, becase there is a delay between open port assigned callbacks. Some of messages may be lost before DB gets initialized. The right way to fix it is:

    var io = null;
    DB.connect(function () {
        io = require('socket.io').listen(8080);
        io.sockets.on('connection', function (socket) {
            console.log("On connection");
            initSockets(socket);
        });
    });
    

提交回复
热议问题