javascript 调用 .disconnect() 后如何重新连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9598900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reconnect after you called .disconnect()
提问by Lionel Chan
Question:How do you reconnect a client to the server after you have issued a manual .disconnect()
?
问题:发布手册后如何将客户端重新连接到服务器.disconnect()
?
In my current project, I need to disconnect a client from the server when the user log out from the session. I did a socket.disconnect()
to do the disconnection successfully. Server removed the user from the session.
在我当前的项目中,当用户从会话中注销时,我需要断开客户端与服务器的连接。我做了一个socket.disconnect()
成功的断开连接。服务器从会话中删除了用户。
After awhile, the user decided to login again, but socket.io refuses to connect.
过了一会儿,用户决定再次登录,但socket.io拒绝连接。
I am clear that Socket.IO has implemented reconnection algorithm but clearly this is a different case.
我很清楚 Socket.IO 已经实现了重新连接算法,但显然这是一个不同的情况。
Below is the piece of code where I do the connection. On second trigger of this block of code, object socket
was created, but no connect
was fired from this object.
下面是我进行连接的一段代码。在此代码块的第二个触发器中,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');
});
UPDATE: As requested by @Tony
更新:根据@Tony 的要求
In fact the whole thing is wrapped under Sencha Touch 2.0, but I believe there is nothing to do with ST2.0
实际上整个东西都包裹在Sencha Touch 2.0之下,但我相信与ST2.0无关
This is my Data Class. Usage of this class is when the user logged in, this class will get initialized. And upon the user logout, the system will call the disconnect()
method in this class.
这是我的数据类。这个类的用法是当用户登录时,这个类会被初始化。并且在用户注销时,系统将调用disconnect()
该类中的方法。
When the user login again, this class is initialized again, but funny is the socket somehow retained all the previous events and sessions it has previously.
当用户再次登录时,这个类再次被初始化,但有趣的是套接字以某种方式保留了它之前的所有事件和会话。
/**
* 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);
}
});
And below is my console.log results:
下面是我的 console.log 结果:
And below is my node.js debug window
下面是我的 node.js 调试窗口
I believe the root cause of this funny scenario is that the previously attached connect
event listener is not removed thoroughly. How should I remove it? Should I use once
? or I should specify the listener function as well. I thought removeAllListeners()
is sufficient for this task.
我相信这个有趣场景的根本原因是之前附加的connect
事件侦听器没有彻底删除。我应该如何删除它?我应该使用once
吗?或者我也应该指定监听器函数。我认为removeAllListeners()
足以完成这项任务。
回答by Tony Abou-Assaleh
The standard approach in latest socket.io is:
最新 socket.io 中的标准方法是:
socket.on('disconnect', function() {
socket.socket.reconnect();
}
This is what I've been using in my app and works great. It also ensures that the socket keeps trying to reconnect if the server goes way, and eventually reconnects when the server is back online.
这是我一直在我的应用程序中使用的,并且效果很好。它还确保套接字在服务器正常运行时继续尝试重新连接,并最终在服务器重新联机时重新连接。
In your case, you need to ensure two things:
在您的情况下,您需要确保两件事:
- You create your socket only once. Don't call
socket = io.connect(...)
more than once. - You setup your event handling only once - otherwise they will be fired multiple times!
- 您只需创建一次套接字。不要
socket = io.connect(...)
多次打电话。 - 您只设置一次事件处理 - 否则它们将被多次触发!
So when you want to reconnect the client, call socket.socket.reconnect()
. You can also test this from the browser console in FireFox and Chrome.
所以当你想重新连接客户端时,调用socket.socket.reconnect()
. 您还可以从 FireFox 和 Chrome 中的浏览器控制台对此进行测试。
回答by Prasad Bhosale
You can reconnect by following client side config.
您可以按照客户端配置重新连接。
// for socket.io version 1.0
io.connect(SERVER_IP,{'forceNew':true };
回答by DrLightman
I'm doing this way with socket.io 1.4.5 and it seems to work, for now:
我正在用 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();
回答by Saurabh Kumar
socket.socket.connect();
gets you reconnected.
让你重新连接。
回答by JT.
It seems to me it is how you handle the disconnect... Worked for me using socket.io - v1.1.0
在我看来,这就是您处理断开连接的方式……使用 socket.io - v1.1.0 对我来说有效
wrong way...
错误道...
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
correct way...
正确的方法...
// 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.
回答by Isaac Pak
socket.io-client v2.2.0
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
}
}