我今天正在进行一些代码重构,我注意到在套接字IO中关闭套接字并不会停止重新连接尝试。想到的唯一解决方案是在关闭套接字时将socketManager.reconnects设置为false,并在我再次连接时将其设置为true,但我也遇到了问题。
当我关闭套接字并将重新连接设置为false时,重新连接尝试按预期停止,但之后我将其设置为true并尝试连接,并且只进行了一次连接尝试,并且它不会再次尝试重新连接。我检查了套接字管理器。重新连接值,它确实设置为true,但重新连接尝试不会发生。
我在这里做错了什么,或者它是库中的错误。这是我的代码。
let socketManager = SocketManager(socketURL: URL(string: Constants.serverSocketURL)!, config: [.log(true), .reconnects(true), .reconnectAttempts(500), .reconnectWait(1)])
lazy var socket = socketManager.defaultSocket
func establishConnection() {
socketManager.reconnects = true
if !self.isConnected() {
print(self.socketManager.reconnects)
socket.connect(timeoutAfter: 7.0) {
Logger.log(message: "Socket connection timeout", event: .i)
}
}
}
func closeConnection() {
turnOffListeners()
socket.disconnect()
socketManager.reconnects = false
}
答案 0 :(得分:1)
如果看不到您的更多代码,将很难找到实际的问题。我现在可以做的是向您展示我在Swift中对Socket.io的实现。也许这会对您有所帮助。
SocketHelper.swift
class SocketHelper: NSObject {
static let shared = SocketHelper()
private let manager = SocketManager(
socketURL: URL(string: ApiConstants.Routes.URL)!,
config: [.forceNew(true)]
)
private var socket: SocketIOClient!
var isConnected: Bool = false
private override init() {
super.init()
socket = manager.defaultSocket
socket.on(clientEvent: .connect, callback: { data, ack in
print("SocketManager: connected")
self.isConnected = true
self.sendNotification(event: "CONNECTED")
})
socket.on(clientEvent: .disconnect, callback: { data, ack in
print("SocketManager: disconnected")
self.isConnected = false
self.sendNotification(event: "DISCONNECTED")
})
}
private func sendNotification(event: String) {
NotificationCenter.default.post(name: NSNotification.Name(event), object: nil)
}
func connect() {
if !isConnected {
socket.connect()
}
}
func disconnect() {
if isConnected {
socket.disconnect()
}
}
}
然后在ViewController中,您应该注册观察者:
NotificationCenter.default.addObserver(self, selector: #selector(socketConnected), name: NSNotification.Name("CONNECTED"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(socketDisconnected), name: NSNotification.Name("DISCONNECTED"), object: nil)
连接到套接字:
SocketHelper.shared.connect()
等待事件:
@objc func socketConnected() {
//connected
}
@objc func socketDisconnected() {
//disconnected
}
答案 1 :(得分:0)
这对我来说很棒,但是,它在完全停止之前又进行了一次尝试。
socket.io-client”:“ 2.2.0”
this.socket.io.reconnectionAttempts(0);