Usage Guide

This section covers detailed usage patterns for SRWebSocket.

Initialization

You can initialize the socket with a simple NSURL or a more complex NSURLRequest if you need to pass custom headers (like Authentication) during the handshake.

// Simple
SRWebSocket *socket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:@"ws://echo.websocket.org"]];

// With Headers
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"wss://secure.api.com"]];
[request setValue:@"Bearer my_token" forHTTPHeaderField:@"Authorization"];
SRWebSocket *socket = [[SRWebSocket alloc] initWithURLRequest:request];

Sending Data

SocketRocket supports sending both UTF-8 Strings and binary NSData.

Sending Text

NSError *error = nil;
[self.webSocket sendString:@"Hello Server" error:&error];
if (error) {
    NSLog(@"Failed to send string: %@", error);
}

Sending Binary

NSData *data = [self.myImage pngData];
NSError *error = nil;
[self.webSocket sendData:data error:&error];

Receiving Data

Data is received via the SRWebSocketDelegate protocol.

Text vs. Data

By default, text frames are converted to NSString. You can override this behavior if you prefer to receive NSData for all frames.

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
    if ([message isKindOfClass:[NSString class]]) {
        // Handle Text
    } else if ([message isKindOfClass:[NSData class]]) {
        // Handle Binary
    }
}

Or implement specific methods:

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(NSString *)string {
    // Handle text only
}

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithData:(NSData *)data {
    // Handle binary only
}

Threading and RunLoops

By default, SRWebSocket schedules its callbacks on the main run loop. However, the heavy lifting (networking I/O) happens on a background thread managed by the library.

If you want the delegate callbacks to occur on a specific queue (to avoid blocking the main UI thread with processing logic):

self.webSocket.delegateDispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

Ping / Pong

The WebSocket protocol includes a Ping/Pong mechanism to keep connections alive.

Sending a Ping:

[self.webSocket sendPing:nil error:nil];

Receiving a Pong: Implement the delegate method:

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload {
    NSLog(@"Pong received");
}