调用.disconnect()后如何重新连接

时间:2012-03-07 09:36:16

标签: javascript node.js websocket socket.io

问题:在您发布手册.disconnect()后,如何将客户端重新连接到服务器?

在我当前的项目中,当用户从会话中注销时,我需要断开客户端与服务器的连接。我做了一个socket.disconnect()来成功断开连接。服务器从会话中删除了用户。

过了一段时间,用户决定再次登录,但socket.io拒绝连接。

我很清楚Socket.IO已经实现了重新连接算法,但显然这是一个不同的情况。

以下是我进行连接的代码段。在此代码块的第二个触发器上,创建了对象socket,但没有从此对象触发connect

//Start the socket
var socket = io.connect(SOCKET_IO_URL);
socket.on('connect', function() {
    me.fireEvent('connect');
    socket.emit('register', {
        hashed_identifier: hashed_identifier,
        account_id: account_id
    });
});

socket.on('ready', function() {
    me.ready = true;
    me.log('Handshake done. Listening for new data');
});

socket.on('data', function(data) {
    me.fireEvent('data', data);
    //Tells server we received it
    socket.emit('data', {ack: 1});
});

socket.on('disconnect', function() {
    me.fireEvent('disconnect');
});

更新:根据@Tony的要求

事实上,整件事情都包含在Sencha Touch 2.0中,但我相信与ST2.0无关

这是我的数据类。这个类的用法是当用户登录时,这个类将被初始化。在用户注销后,系统将调用此类中的disconnect()方法。

当用户再次登录时,此类会再次初始化,但有趣的是套接字以某种方式保留了之前的所有先前事件和会话。

/**
* Serve as interface to wait for data communication in between server and client
*/
Ext.define('go.module.connect.Data', {

    mixins: {
        observable: 'Ext.mixin.Observable'
    },

    config: {
        account: null
    },

    ready: false,

    socket: null,

    constructor: function(cfg) {
        var me = this,
            hashed_identifier = Sha1.hash(go.__identifier);


        me.initConfig(cfg);

        var account_id = me.getAccount().get('id');

        //Start the socket
        var socket = io.connect(SOCKET_IO_URL);
        socket.on('connect', function() {
            console.log('connect');
            me.fireEvent('connect');
            socket.emit('register', {
                hashed_identifier:hashed_identifier,
                account_id: account_id
            });
        });

        socket.on('ready', function() {
            me.ready = true;
            me.log('Handshake done. Listening for new data');
        });

        socket.on('data', function(data) {
            me.fireEvent('data', data);
            //Tells server we received it
            socket.emit('data', {ack: 1});
        });

        socket.on('disconnect', function() {
            me.fireEvent('disconnect');
        });

        console.log(socket);
        if (!socket.socket.connected){
            socket.socket.reconnect();
        }


        me.socket = socket;


        me.callParent([cfg]);
    },

    disconnect: function() {
        this.socket.disconnect();
        this.socket.removeAllListeners();
        this.socket.socket.removeAllListeners();
    },

    log: function(msg) {
        console.log('@@ Connect: '+msg);
    }
});

以下是我的console.log结果:

Console screenshot

以下是我的node.js调试窗口

Node.js debug window

我认为这个有趣场景的根本原因是之前附加的connect事件侦听器未被彻底删除。我应该如何删除它?我应该使用once吗?或者我也应该指定监听器功能。我认为removeAllListeners()足以完成此任务。

7 个答案:

答案 0 :(得分:13)

最新socket.io中的标准方法是:

socket.on('disconnect', function() {
    socket.socket.reconnect();
}

这是我在我的应用程序中使用的并且效果很好的。它还确保套接字在服务器运行时继续尝试重新连接,并在服务器重新联机时最终重新连接。

在您的情况下,您需要确保两件事:

  1. 您只创建一次套接字。不要多次拨打socket = io.connect(...)
  2. 您只设置一次事件处理 - 否则会多次触发它们!
  3. 因此,当您想重新连接客户端时,请致电socket.socket.reconnect()。您还可以在FireFox和Chrome浏览器控制台中对此进行测试。

答案 1 :(得分:2)

您可以按照客户端配置重新连接。

 // for socket.io version 1.0
io.connect(SERVER_IP,{'forceNew':true };

答案 2 :(得分:1)

在我看来,你是如何处理断开连接的...... 使用socket.io - v1.1.0

为我工作

错误的方式......

var sock = io( '/' );
sock.on( 'connect', function(x) { console.log( 'Connected', x ); } );
// now we disconnect at some point:
sock.disconnect();
// now we try to reconnect...
sock.connect()
// or    
sock.reconnect();
// - both seem to create the new connection in the debugger, all events are missing though

正确的方式......

// As above with 3 extra characters, everything functions as expected...
//events fire properly...
sock.io.disconnect();
// consequently i'm also using (for consitency)
sock.io.reconnect();
// sock.connect() still seems to work however.

答案 3 :(得分:1)

我正在使用socket.io 1.4.5这样做,它现在似乎有效:

var app = {
    socket: null,
    connect: function() {
      // typical storing of reference to 'app' in this case
      var self = this;
      // reset the socket
      // if it's not the first connect() call this will be triggered
      // I hope this is enough to reset a socket
      if( self.socket ) {
        self.socket.disconnect();
        delete self.socket;
        self.socket = null;
      }
      // standard connectiong procedure
      self.socket = io.connect( 'http://127.0.0.1:3000', { // adapt to your server
        reconnection: true,             // default setting at present
        reconnectionDelay: 1000,        // default setting at present
        reconnectionDelayMax : 5000,    // default setting at present
        reconnectionAttempts: Infinity  // default setting at present
      } );
      // just some debug output
      self.socket.on( 'connect', function () {
        console.log( 'connected to server' );
      } );
      // important, upon detection of disconnection,
      // setup a reasonable timeout to reconnect
      self.socket.on( 'disconnect', function () {
        console.log( 'disconnected from server. trying to reconnect...' );
        window.setTimeout( 'app.connect()', 5000 );
      } );
    }
} // var app


app.connect();

答案 4 :(得分:0)

socket.socket.connect();

让你重新连接。

答案 5 :(得分:0)

socket.io v2.0(当前)

对于正在寻找我最新版本的人们,请找到以下文档摘录:

要手动重新连接:

socket.on('disconnect', () => {
  socket.open();
});

答案 6 :(得分:-1)

socket.io-client v2.2.0

import io from "socket.io-client"

var socket = io(url)  // initial connection

const reconnect = () => {
  if(!socket.connected) {
    socket = io(url)  // reconnects to a new socket
  }
}