如何在Socket.IO中模拟连接失败
How to simulate a connection failure in Socket.IO
我正在开发一个应用程序,其中客户端通过Socket连接到nodejs服务器。IO和订阅各种事件。这些订阅相当复杂,无法用Socket处理。IO的通道特性。
这意味着客户端需要跟踪其订阅,并且在断开连接时可能必须重新订阅。不幸的是,我不太确定Socket。IO处理重新连接,以及它对客户端的透明度。
所以这里有一个问题:我如何模拟连接失败并强制Socket。IO重新连接?
插座。io在套接字对象中为您提供事件。实际上,你可以通过阅读它们的API来找到各种工具。
参见stackoverflow的这个例子套接字。IO处理断开连接事件
根据我的经验,我发现这是最简单和有用的解决方案:
客户端:
// the next 3 functions will be fired automatically on a disconnect.
// the disconnect (the first function) is not required, but you know,
// you can use it make some other good stuff.
socket.on("disconnect", function() {
console.log("Disconnected");
});
socket.on("reconnect", function() {
// do not rejoin from here, since the socket.id token and/or rooms are still
// not available.
console.log("Reconnecting");
});
socket.on("connect", function() {
// thats the key line, now register to the room you want.
// info about the required rooms (if its not as simple as my
// example) could easily be reached via a DB connection. It worth it.
socket.emit("registerToRoom", $scope.user.phone);
});
服务器端:
io.on('connection', function(socket){
socket.on("registerToRoom", function(userPhone) {
socket.join(userPhone);
});
});
就是这样。非常简单直接。
您还可以在连接的套接字(最后一个函数)中为用户显示添加更多更新,例如刷新其索引或其他内容。
相关文章:
- 在VanillaJS中模拟模型双向数据绑定
- 是否可以将一个函数输入连接到另一个函数调用的文本
- 使用jasmine模拟对服务器的调用
- 如何使用密码检测网络中的状态连接
- 如何处理node.js节点mongodb中的连接和查询队列
- Rails-JQueryUIAutcomplete和AJAX不工作,可以't连接到数据库
- 模拟谷歌地图中的点击
- Twilio-显示所有连接参与者的远程参与者视频
- 操作放置在画布上的元素之间的连接
- TypeError:_this.store.getState在使用来自Redux的连接时不是函数
- jQuery UI可排序-多连接列表拖动
- 如何使用offer/answer交换来自两个对等连接的流
- 使用模拟按键在输入框中自动输入文本
- 模拟chrome.storage.local函数使用Jasmine
- 在Qualtrics中,介绍如何动态连接两个滑块
- 从数据库中检索字段,而不模拟它们
- 模拟连接错误
- Node.JS 模拟 1000/+ 客户端连接的客户端应用
- 如何在Socket.IO中模拟连接失败
- 无法连接猫鼬和模拟鹅