URLSessionWebSocketTask - response to ping from server with client pong
Asked Answered
S

1

6

I use the Apple-provided URLSessionWebSocketTask to set up a websocket. I receive, send messages and can send a ping. But how should I receive and respond to 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 piece of code, but what should I implement to respond to a ping from the connected server? I did read several docs but couldn't find anything, any pointers or suggestions.

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 did I do I wrong?

Stonehenge answered 11/2, 2021 at 11:15 Comment(0)
P
2

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

Postwar answered 8/6, 2022 at 16:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.