nic*_*ng2 10 javascript sockets node.js socket.io swift
所以我有一个 Swift 客户端、Node.js 服务器,并且正在使用 socket.io。我遇到一个问题,当用户在连接到服务器时从 WiFi 更改为 LTE(被动地,如果他们手动关闭 wifi,则可以正常工作)时,由于某种原因,他们不会重新连接到服务器(只是遇到 ping 超时) )。我尝试将 ping 超时增加到 50 秒,但没有效果。我的用户在连接到同一个房间时相互交互,所以这是一个大问题。
我在客户端的连接代码如下所示:
var socket: SocketIOClient?
fileprivate var manager: SocketManager?
func establishConnection(_ completion: (() -> Void)? = nil) {
let socketUrlString: String = serverURL
self.manager = SocketManager(socketURL: URL(string: socketUrlString)!, config: [.forceWebsockets(true), .log(false), .reconnects(true), .extraHeaders(["id": myDatabaseID])])
self.socket = manager?.defaultSocket
self.socket?.connect()
//self.socket?.on events go here
}
Run Code Online (Sandbox Code Playgroud)
在客户端,我的连接代码如下所示:
const io = require('socket.io')(http, {
pingTimeout: 10000
});
io.on('connection', onConnection);
function onConnection(socket){
let headerDatabaseID = socket.handshake.headers.id
//in the for loop below, I essentially disconnect any socket that has the same database ID as the one that just connected (in this case, when a client is in a room with other clients,
//and then he/she switches from WiFi to LTE, the client reconnects to the socket server and this removes the old connection from the room it was in)
for (let [id, connectedSocket] of io.sockets.sockets) {
if (connectedSocket.databaseID == headerDatabaseID && socket.id != id) {
connectedSocket.disconnect()
break
}
}
//socket.on() events here
}
Run Code Online (Sandbox Code Playgroud)
我的问题是——当客户端进行被动网络切换(WiFi -> LTE 或反之亦然)时,我该如何重新连接客户端?我认为只添加 .reconnects(true) 就可以了,但由于某种原因,它不是......
如果我可以更详细/有帮助,或者您想查看其他代码,请告诉我。
我相信解决您问题的方法可以很简单,也可以很复杂;这取决于您的要求。我假设每个聊天室都有自己的 ID。
如果您将该 ID 存储在设备的内存中,当用户重新连接时,您可以让套接字重新连接到您上次拥有的房间 ID,并且他们将重新加入该房间。这是不安全的。
如果房间受到保护并且不是公开的,那么如果某人知道/可以猜测房间 ID,则他们可能能够连接到不允许他们进入的房间。为了解决这个问题,您需要实现某种身份验证或服务器端数据库来跟踪此类内容。