【发布时间】:2021-12-16 04:52:07
【问题描述】:
所以我有一个 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
}
在客户端,我的连接代码如下:
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
}
我的问题是——当客户端进行被动网络切换(WiFi -> LTE,反之亦然)时,我该如何重新连接客户端?我认为只需添加 .reconnects(true) 即可,但由于某种原因,它不是...
如果我可以更详细/有帮助,或者如果您想查看其他代码,请告诉我。
【问题讨论】:
标签: javascript node.js swift sockets socket.io