I'm trying to use the new Network.framework to connect to WebSocket but facing nil handshake response from server.
(Yes, I know Starscream exist but it didnt support Proxy / Mobility of user switching between network interface)
My test code:
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)
})
}
It's nil response and connection dropped instead of getting Upgrade handshake response from server, below with console logs:
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]
Can anyone guide me how to utilize Apple new Network.framework? It will be much appreciated!
Update1
My bad, I'm now able to see the handshake response with using
.ascii
encoding instead of.utf8
.But I'm still having connection dropped
Connection reset by peer
. How do I retain the connection after upgrade to WebSocket?
You should follow the Websocket guidelines how to format Websocket sent message.
I think this is a good resource. I used it myself.
https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers