我正在尝试使用新的 Network.framework 连接到 WebSocket,但面临来自服务器的零握手响应。
(是的,我知道红蜘蛛存在,但它不支持代理/移动用户在网络接口之间切换)
我的测试代码:
func beginTest() {
let connection = NWConnection(host: "echo.websocket.org", port: 443, using: .tls)
connection.stateUpdateHandler = { state in
print("State:", state)
switch state {
case .ready:
self.connectionReady(connection)
default:
break
}
}
connection.start(queue: .main)
}
func connectionReady(_ connection: NWConnection) {
let raw = """
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: echo.websocket.org
Origin: https://echo.websocket.org
Sec-WebSocket-Key: s04nPqA7M6pQ3Lu2jRJLSQ==
Sec-WebSocket-Version: 13
"""
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: .utf8))
}
print("Error:", error)
let hello = "Hello".data(using: .utf8)
connection.send(content: hello, completion: .idempotent)
})
}
这是零响应和连接断开,而不是从服务器获取升级握手响应,下面带有控制台日志:
State: preparing
State: ready
Received: nil
Error: nil
2018-10-08 11:38:57.314885+0800 SwiftNetworkTest[86448:3026660] [] nw_socket_handle_socket_event [C1.1:2] Socket SO_ERROR [54: Connection reset by peer]
谁能指导我如何使用 Apple 新的 Network.framework?将不胜感激!
更新1
我的错,我现在可以使用
.ascii
encoding 而不是.utf8
.但我仍然有连接断开
Connection reset by peer
。升级到 WebSocket 后如何保持连接?