我开发了一个聊天应用程序,该应用程序使用Socket.io进行实时消息传递。
在localhost上,一切正常,但是在真实设备上,一切正常。
问题在于重新连接。如果我设置了reconnects = true
,则它每半秒就会连接和断开连接。
如果我禁用了该功能,并在几秒钟后手动使用socket.connect()
,它不会产生怪异的行为。
为什么会这样?
class SocketIOManager: NSObject, URLSessionDelegate {
static var shared = SocketIOManager()
var setuppedManager : Bool = false
var manager : SocketManager!
let socket : SocketIOClient!
var authenticated : Int = 0
override init() {
self.setuppedManager = false
manager = SocketManager(socketURL: URL(string: "https://example.com/node")!, config: [.log(true), .compress, .reconnects(false), .secure(true), .path("/node/socket.io/")])
self.socket = manager.defaultSocket
super.init()
}
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}
func establishConnection() {
manager.handleQueue.async {
self.socket.connect()
}
}
func closeConnection() {
manager.handleQueue.async {
self.socket.disconnect()
self.socket.removeAllHandlers()
}
}
func setUpManager(completion: @escaping (ActionResult?)->()){
if setuppedManager {
return
}
setuppedManager = true
manager.handleQueue.async {
self.socket.on("connect") { data, ack in
self.socket.emit("authenticate", ["token" : chatToken.token ])
NotificationCenter.default.post(name: .socketIOStatusChanged, object: nil, userInfo: nil)
}
self.socket.on("disconnect"){ data, ack in
NotificationCenter.default.post(name: .socketIOStatusChanged, object: nil, userInfo: nil)
}
self.socket.on("reconnect"){ data, ack in
NotificationCenter.default.post(name: .socketIOStatusChanged, object: nil, userInfo: nil)
}
self.socket.on("reconnectAttempt"){ data, ack in
NotificationCenter.default.post(name: .socketIOStatusChanged, object: nil, userInfo: nil)
}
self.socket.on("authenticated") { data, ack in
self.authenticated = 1
self.socket.emit("subscribe")
NotificationCenter.default.post(name: .socketIOStatusChanged, object: nil, userInfo: nil)
}
self.socket.on("unauthorized") { data, ack in
self.authenticated = -1
NotificationCenter.default.post(name: .socketIOStatusChanged, object: nil, userInfo: nil)
}
}
}
}
最初我使用以下配置:
.reconnects(true), .reconnectAttempts(-1), .reconnectWait(4),
但是正如我所指出的,它导致了一个连接与断开的无休止循环。
io.sockets.on('connect', socketioJwt.authorize({
secret: 'mySecret',
timeout: 10000,
reconnection: false,
reconnectionAttempts: -1,
forceNew: false,
rejectUnauthorized : false
})).on('authenticated', function(socket) {
...
}