Using NSURLSession to create webSocket that can receive async messages from server.

Hi,

I've got an object from type NSURLSessionWebSocketTask from which I create webSocket.

However, currently it can only receive responses as can be seen here:

   NSURLSessionWebSocketMessage * msg = [[NSURLSessionWebSocketMessage alloc] initWithString:myStringBody;
  [socketConnection sendMessage:msg completionHandler: ^(NSError * e) {
    if (e == nil) {
      [socketConnection receiveMessageWithCompletionHandler:^(NSURLSessionWebSocketMessage * _Nullable message, NSError * _Nullable error) {
       NSLog(@"got message = %@", message.string);
      }];
  }];

I'd like to be able to receive messages from server that wasn't triggered from client request (messages that initiated by the server).

Ideally, i wish to get them in some sort of queue (maybe NSOperationQueue or dispatch queue). But the bottomline should be that some listener would work in the background.

Perhaps there's some delegate to implement this requirement ?

Answered by DTS Engineer in 679801022

I'd like to be able to receive messages from server that wasn't triggered from client request

In that case just call -receiveMessageWithCompletionHandler: and, when that completes, if it completed successfully, call it again to queue up the next read.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Accepted Answer

I'd like to be able to receive messages from server that wasn't triggered from client request

In that case just call -receiveMessageWithCompletionHandler: and, when that completes, if it completed successfully, call it again to queue up the next read.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Ok, So i've implemented my receive function to call new receiveMessageWithCompletionHandler upon successful completion and it's working great.

But now I've got another issue in the same area...

If I'm sendPingWithPongReceiveHandler method as a webSocket heartbeat, how can I ensure that the Pong responses wouldn't get caught by the receiveMessage completion handler, but by the pongReceiveHandler ?

Are the Pong responses differ from other responses in terms of routing so that each trigger a different callback by design ?

Are the Pong responses differ from other responses in terms of routing so that each trigger a different callback by design ?

Yes. I recommend that you have a read of RFC 6455 (Internet RFCs, unlike most standard documents, and generally very easy to read). Section 5 describes how WebSocket framing works, explaining that control frames, like ping and ping, are distinct from data frames.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Using NSURLSession to create webSocket that can receive async messages from server.
 
 
Q