我正在使用 Swift 通过 websockets 将 iOS 应用程序连接到 LG 智能电视(都在同一个 wifi 网络上),每次连接都会收到成功消息,然后在不到一秒的时间内断开连接。下面是我用来建立连接的代码。我屏蔽了电视 IP 地址,但已确认我使用的是正确的 IP 地址。
public init(){
self.request = URLRequest(url: URL(string: "ws://192.xxx.x.xx:3000")!)
self.socket = WebSocket(request: request)
self.socket.delegate = self
}
public func connect(){
print("in connect")
self.socket.connect()
print("end of connect")
}
func didReceive(event: WebSocketEvent, client: WebSocket) {
switch event {
case .connected(_):
print("WebSocket is connected")
case .disconnected(let reason, let code):
print("Disconnected: code=\(code), reason=\(reason)")
case .text(let message):
print("Received: \(message)")
case .binary(_):
print("binary")
break
case .pong(_):
print("pong")
break
case .ping(_):
print("ping")
break
case .error(let error):
print(error ?? "")
case .viabilityChanged(_):
print("viability changed")
break
case .reconnectSuggested(_):
print("reconnect suggested")
break
case .cancelled:
print("WebSocket is cancelled")
}
}
当在单独的视图上按下按钮时,会调用 connect() 方法,我可以根据打印消息判断它正在工作。这是我每次得到的输出
in connect
end of connect
viability changed
WebSocket is connected
Disconnected: code=1008, reason=invalid origin
WebSocket is cancelled
我试过搜索这个 1008 错误代码,但它看起来很通用。我是 websockets/网络编程的新手,如果有任何帮助,我将不胜感激