How to use URLSessionWebSocketTask + URLProtocol properly

584 views Asked by At

Http connection + URLProtocol works fine. But now I try to include websockets in this scheme and it hasn't been working. Here is websockets level:

var urlSession =  URLSession(configuration: myConfiguration, delegate: nil, delegateQueue: .main)  
var urlSessionWebSocketTask = urlSession.webSocketTask(with: URL(string: "ws://..." ))
urlSessionWebSocketTask.receive(completionHandler: { result in  ... }
urlSessionWebSocketTask.resume() 

resume() from URLSessionWebSocketTask starts a connection process. On URLProtocol level I catch this URLRequest, send it to a server and get Switching Protocols URLResponse with websocket message (data).

Here is override the URLProtocol method:

open class MyProtocol: URLProtocol {
     ....     
override open func startLoading() { 

    // Get response and data here...  
     
     self.client.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
     self.client.urlProtocol(self, didLoad: data)
     self.client.urlProtocolDidFinishLoading(self)
}     
}

I call three URLProtocol methods for returning data back and then I get errors:

  • webSocket: Connection not set before response is received, failing task
  • webSocket[] Task <>.<> finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost.

What seems to be the problem? Something with returning result back to WebSocketTask, but I don't understand what I'm doing wrong. My question is how to use websockets + URLProtocol together?

Would appreciate any help

I'm sure I've got a correct URLResponse and a websocket message. I checked it using different http clients and Wireshark. Header fields like "Sec-WebSocket-Accept" in Request and Response correspond to RFC 6455.

0

There are 0 answers