我发现以下代码可以处理使用Apple Network Framework的Websocket,并且运行良好:
let connection = NWConnection(host: "**.**.**.**", port: ****, using: .tcp)
override func viewDidLoad() {
super.viewDidLoad()
connection.stateUpdateHandler = { state in
print("State:", state)
switch state {
case .ready:
self.connectionReady(self.connection)
case .cancelled:
print("cancelled")
default:
break
}
}
connection.start(queue: .main)
}
func connectionReady(_ connection: NWConnection) {
let raw = """
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: ************************
Host: **.**.**.**:****
"""
let rawData = raw.appending("\n\n\n").replacingOccurrences(of: "\n", with: "\r\n").data(using: .utf8)
connection.send(content: rawData!, completion: .idempotent)
connection.receiveMessage(completion: {data, context, bool, error in
if let data = data {
print("Received:", String(data: data, encoding: .ascii) ?? "no string")
}
})
}
控制台输出正是我想要的:
State: preparing
State: ready
Received: HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: ****************************
现在我想对Starscream进行同样的操作,但是我什么也没收到,我也不知道为什么。希望有人能帮忙。这是我的代码:
let socket = WebSocket(url: URL(string: "ws://**.**.**.**:****/")!)
var rawData: Data!
override func viewDidLoad() {
super.viewDidLoad()
let raw = """
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: ************************
Host: **.**.**.**:****
"""
rawData = raw.appending("\n\n\n").replacingOccurrences(of: "\n", with: "\r\n").data(using: .utf8)
socket.connect()
}
func websocketDidConnect(socket: WebSocketClient) {
print("connect")
socket.write(data: rawData)
}
func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
print("disconnect")
print(error?.localizedDescription)
}
func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
print("receiveMessage")
print(text)
}
func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
print("receiveData")
print(data)
}
现在我什么也没收到。它会连接,然后立即断开连接,我收到错误消息“操作无法完成”。控制台输出:
connect
disconnect
Optional("The operation couldn’t be completed. (Starscream.WSError error 1.)")
答案 0 :(得分:0)
好的,我找到了原因。 我必须使用AdvancedDelegate来获得相同的输出。 但是也许有人可以告诉我为什么它会立即断开并显示错误消息“操作无法完成”