mod*_*tor 5 javascript sockets node.js socket.io
我有使用Socket.io的问题.
代码很简单:
var socket = null;
var socketInit = false; //if it is true, use reconnect
...
function connect() {
if(!socketInit) {
socket = io();
socketInit = true;
//attach event handlers
socket.on('connect', function() {
console.log('connect fired!');
});
socket.on('disconnect', function() {
console.log('disconnect fired!');
});
socket.on('reconnect', function() {
console.log('reconnect fired!');
});
}
else {
socket.io.connect();
}
}
...
function disconnect() {
socket.disconnect();
}
Run Code Online (Sandbox Code Playgroud)
如您所见,有两个连接或断开套接字的功能.在connect函数中,它将'connect','disconnect','reconnect'处理程序连接到套接字.
首先我称之为连接功能,效果很好.服务器端也运行良好.我称之为断开连接功能,也适用于服务器.
但我再次调用connect函数,这意味着"socketInit"变量为true,所以connect函数尝试:
socket.io.connect();
Run Code Online (Sandbox Code Playgroud)
我检查了服务器和客户端控制台,看起来它已连接,但问题是事件没有被触发!
服务器端'connection'事件在重新连接时被触发,但客户端'connect'或'reconnect'事件未被触发.我试图找出发生了什么,但我仍然没有得到它.我多次检查Web控制台和服务器控制台,并且连接本身工作正常,但问题是事件无法正常工作!
如果有人知道,我将非常感谢帮助我.谢谢 ;)
ps我试图添加'reconnected','reconnection','reconnect_error'事件处理程序,但两者都不起作用.
如果您使用的是 Socket.io 1.0,请尝试使用套接字上的 io 管理器来处理手动断开连接和重新连接。
var socket = null;
var socketInit = false;
function connect() {
if(!socketInit) {
socket = io();
socketInit = true;
//attach event handlers
socket.on('connect', function() {
console.log('connect fired!');
});
socket.on('disconnect', function() {
console.log('disconnect fired!');
});
socket.on('reconnect', function() {
console.log('reconnect fired!');
});
}
else {
socket.io.reconnect();
}
}
function disconnect() {
socket.io.disconnect();
}
Run Code Online (Sandbox Code Playgroud)
套接字上的 reconnecting_attempt、reconnecting、reconnected 和 connected 事件都应该在之后发出。
| 归档时间: |
|
| 查看次数: |
9166 次 |
| 最近记录: |