我正在尝试订阅本地网络中 Mac 上托管的 Websocket。但它几乎在连接后立即断开连接。我可以发送消息,我可以在我的 Mac 上看到它正在接收它们(至少是命令),但它会立即断开连接。
它应该像这样工作:我连接我发送一个 json 格式的字符串:({"+":["v.altitude"]}
订阅高度) Websocket 定期响应{"v.altitude":71.323}
我在我的 Mac 上使用 websocoat 在本地尝试了它,它看起来像这样:[图片] ( https://ibb.co/JqjFSs7 )
Xcode 控制台输出以下内容:
连接。
连接的。
DISCONNECTED 可选(“操作无法完成(Starscream.WSError 错误 1.)”)。
import UIKit
import Starscream
class ViewController: UIViewController, WebSocketDelegate, WebSocketPongDelegate {
func websocketDidReceivePong(socket: WebSocketClient, data: Data?) {
print("PONG")
}
var websocket: WebSocket = WebSocket(url: URL(string: "ws://192.168.178.23:8085/datalink")!)
let jsonObject: [String: Any] = ["run":["f.light"]]//["+":["v.altitude", "v.lightValue", "v.gearValue"]]
let dic: NSDictionary = ["run" : ["f.light"]]
var components = URLComponents()
override func viewDidLoad() {
components.scheme = "ws"
components.host = "192.168.178.23"
components.path = "/datalink"
components.port = 8085
let url = components.url
super.viewDidLoad()
print(url!)
websocket = WebSocket(url: url!)
websocket.delegate = self
print("Connecting")
websocket.connect()
}
func websocketDidConnect(socket: WebSocketClient) {
print("CONNECTED")
let messageString = "{\"run\":[\"f.light\"]}"
websocket.write(string: messageString)
}
func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
print("DISCONNECTED \(error?.localizedDescription)")
}
func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
print("MESSAGE: STRING")
}
func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
print("MESSAGE: DATA")
}
}