Swift5 - URLSessionWebSocketTask - response to ping from server with client pong

Viewed 274

I use the by Apple provided URLSessionWebSocketTask to setup a websocket. I receive, send messages and can send a ping. But how should I receive and respond of a ping coming from a ws server? I have to work with a server that sends a ping to clients to check if they still are alive. If I receive something from the server, how can I recognise a ping from that server? Is there some keycode in a received message?

func receive() {
    webSocketTask.receive { result in
        print(result)
        switch result {
        case .failure(let error):
                print("Failed to receive message: \(error)")
                ....
        case .success(let message):
            switch message {
            case .data(let data):
                print("\(data)")
                ....
            case .string(let text):
                print("\(text)")
                .....

            @unknown default:
                            fatalError()
            }
        }
        receive()
    }
}

Above is of course a common code piece, but what should I implement to respond to a ping from the connected server. I did read several doc's but couldn't find anything, any pointers or suggestions.

edit: I did found the following OpCode 0x9 and 0xA. Are those Ping and Pong? Could I send a 0x9 as ping and for pong a 0xA? If I try this as text message but I get no reaction. Should it be a frame? So what do I wrong.

Thank you.

1 Answers

It took some digging but you have to set the Opcode to .pong in the NWProtocolWebSocket.Metadata object which then goes into your context parameter in the NWconnection.send function. Your data should mirror what was sent in the ping.

  let metadata = NWProtocolWebSocket.Metadata(opcode: .pong)
  let context = NWConnection.ContentContext(identifier: "context", metadata: [metadata])
    
  client.send(content: data, contentContext: context, isComplete: true, completion: .contentProcessed({ error in
        if let error = error {
            print(error.localizedDescription)
        } else {
            // no-op
        }
    }))

client in this case is your NWConnection

Related