我正在制作一个iOS应用程序,我在其中使用socket.io。场景非常简单,一个人预订冒险,即使用 emit 命令发送数据。之后,我使用 socket.on 来从服务器获取响应。这在某个时候工作得很好,但现在我遇到了问题。数据都没有到达服务器,也没有响应。 我搜索了这个问题,我得到的理解是:
套接字断开连接有一点,因此它停止工作。我甚至在发送数据之前使用了socket.reconnect
但它没有用。
我为node.js找到了forceNew
的参数,但在swift中找不到任何替代方法。
这是我的代码(与socket.io相关):
在AppDelegate中:
AppDelegate.socket = SocketIOClient(socketURL: URL(string: "######")!, config: [.log(true), .compress])
AppDelegate.socket.connect ()
在ViewController中:
override func viewDidLoad() {
super.viewDidLoad()
socket = AppDelegate.socket
self.socket.on("book-adventure-seeker") {[weak self] data, ack in
print (data)
}
}
@IBAction func bookAdventureTapped(_ sender: Any) {
let jwtToken = UserDefaults.standard.string(forKey: "jwtToken")
let data = ["adventure_id": adventureId, "jwt": jwtToken] as [String : Any]
self.socket.emit("book-adventure", data)
}
日志是:
2017-10-20 09:45:04.665 CuufyPrototype[2591:94370] LOG SocketEngine: Writing ws: has data: false
2017-10-20 09:45:08.541 CuufyPrototype[2591:93618] LOG SocketIOClient: Emitting: 2["book-adventure",{"jwt":"######","adventure_id":"######"}]
2017-10-20 09:45:08.541 CuufyPrototype[2591:94370] LOG SocketEngine: Sending ws: as type: 2
SocketIOClientStatus
2017-10-20 09:45:22.804 CuufyPrototype[2591:94370] LOG SocketEngine: Writing ws: 2["book-adventure",{"jwt":"######","adventure_id":"#####"}] has data: false
2017-10-20 09:45:22.805 CuufyPrototype[2591:94370] LOG SocketEngine: Sending ws: 2["book-adventure",{"jwt":"#######","adventure_id":"######"}] as type: 4
2017-10-20 09:45:22.807 CuufyPrototype[2591:94370] LOG SocketEngine: Writing ws: has data: false
2017-10-20 09:45:22.807 CuufyPrototype[2591:94370] LOG SocketEngine: Sending ws: as type: 2
2017-10-20 09:45:22.810 CuufyPrototype[2591:93661] ERROR SocketEngine:
2017-10-20 09:45:22.811 CuufyPrototype[2591:93618] ERROR SocketIOClient:
2017-10-20 09:45:22.811 CuufyPrototype[2591:93618] LOG SocketIOClient: Handling event: error with data: [""]
2017-10-20 09:45:22.811 CuufyPrototype[2591:93618] LOG SocketIOClient: Handling event: statusChange with data: [SocketIO.SocketIOClientStatus]
2017-10-20 09:45:22.812 CuufyPrototype[2591:93618] LOG SocketIOClient: Starting reconnect
2017-10-20 09:45:22.812 CuufyPrototype[2591:93618] LOG SocketIOClient: Handling event: reconnect with data: [""]
2017-10-20 09:45:22.812 CuufyPrototype[2591:93618] LOG SocketIOClient: Trying to reconnect
2017-10-20 09:45:22.812 CuufyPrototype[2591:93618] LOG SocketIOClient: Handling event: reconnectAttempt with data: [-1]
2017-10-20 09:45:22.812 CuufyPrototype[2591:93618] LOG SocketIOClient: Handling event: statusChange with data: [SocketIO.SocketIOClientStatus]
即使我尝试在AppDelegate中使用socket.on
,如下所示:(例如来自官方文档)
AppDelegate.socket = SocketIOClient(socketURL: URL(string: "#######")!, config: [.log(true), .compress])
AppDelegate.socket.on("book-adventure-seeker") {[weak self] data, ack in
print (data)
}
AppDelegate.socket.connect ()
但它仍然不适合我。
更新:有时在使用emit命令时,Engine is being closed
会出现在日志中,但我不知道如何解决此问题。