'How can I detect a server ping using URLSessionWebSocketTask?

Using URLSessionWebSocketTask, a server ping is automatically responded to by a pong from the client.

Still, can the client observe that a ping/pong occurred?

(a related but different question)



Solution 1:[1]

Usually, right after setting a connection, you'd need to run ping in a loop in the app:

  Timer.TimerPublisher(interval: 10, runLoop: .main).sink(receiveValue: { _ in
    task.sendPing(pongReceiveHandler: { error in
      guard let error = error else {
        log("Received pong")
        return
      }

      // Handle error
    })
  }).store(in: &subscriptions)

UPD:

If you're interested in observing pong, then in subscription, check if you received 0x9 as a data:

task.receive { result in
  switch result {
  case .success(let message):
    switch message {
    case .data(let data):
      //
    ...
    }
  ...
  }
}

It will be:

close connection: 0x8
ping: 0x9
pong: 0xA

So you can create an enum:

enum Code: UInt8 {
  case closeConnection = 0x8
  case ping = 0x9
  case pong = 0xA
}

And initialise it with data you receive: Code(rawValue: YOURDATA)

Or you can send "PING" as a text from your cloud server instead, that will simplify things for you

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1