There are two barriers that you will immediately have to solve for here; first, is adding the WebSocket frame protocol to an existing TCP connection after it has been started. For example:
Code Block swiftlet webSocketOptions = NWProtocolWebSocket.Options() |
NWParameters.defaultProtocolStack.applicationProtocols.insert(webSocketOptions, at: 0) |
The next is building an HTTP stack on top of a TCP connection. NWConnection / NWListener are low level network APIs that typically talk TCP or UDP at the transport layer. If you wanted to talk HTTP on top of TCP, you would essentially be in charge of building your own HTTP stack on top of NWConnection. Knowning that, your HTTP stack will need to process the Upgrade headers for WebSocket connections, to make HTTP/TCP connections talk WebSockets; essentially adding the frame protocol I included above while simultaneously not restarting the connection. This is a difficult process. For more on this see RFC 7230, 6.7 - Connection Upgrade. If you run completely out of options here, I know SwiftNIO has functionality that supports this.
Matt Eaton
DTS Engineering, CoreOS
meaton3@apple.com