### Setup TestChat Server Dependencies Source: https://github.com/facebookincubator/socketrocket/blob/main/README.md Install necessary dependencies for the TestChat server. First, ensure the virtual environment is set up by running 'make test'. Then, activate the environment and install tornado. ```bash source .env/bin/activate pip install git+https://github.com/tornadoweb/tornado.git ``` -------------------------------- ### Start TestChat Server (Python) Source: https://github.com/facebookincubator/socketrocket/blob/main/README.md Start the Python-based chatroom server in the activated virtual environment. ```bash python TestChatServer/py/chatroom.py ``` -------------------------------- ### Start TestChat Server (Go) Source: https://github.com/facebookincubator/socketrocket/blob/main/README.md Navigate to the Go chatroom server directory and run the server using 'go run'. ```bash cd TestChatServer/go go run chatroom.go ``` -------------------------------- ### Install SocketRocket with Carthage Source: https://github.com/facebookincubator/socketrocket/blob/main/README.md Add this line to your Cartfile to use SocketRocket with Carthage. Run 'carthage update' to get the latest version. ```plaintext github "facebook/SocketRocket" ``` -------------------------------- ### Install SocketRocket with CocoaPods Source: https://github.com/facebookincubator/socketrocket/blob/main/README.md Add this line to your Podfile to include SocketRocket in your project. Run 'pod install' afterwards. ```ruby pod 'SocketRocket' ``` -------------------------------- ### Run SocketRocket Tests Source: https://github.com/facebookincubator/socketrocket/blob/main/README.md Execute the short test suite from the command line using 'make test'. For all tests, including performance tests, use 'make test_all'. ```bash make test ``` ```bash make test_all ``` -------------------------------- ### Initialize SRWebSocket with URL Source: https://context7.com/facebookincubator/socketrocket/llms.txt Use this method for basic WebSocket connection establishment to a specified server endpoint. ```objective-c #import // Basic initialization with URL SRWebSocket *webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:@"wss://echo.websocket.org"]]; // Set delegate to receive callbacks webSocket.delegate = self; // Open the connection [webSocket open]; ``` -------------------------------- ### Initialize SRWebSocket with Sub-Protocols Source: https://context7.com/facebookincubator/socketrocket/llms.txt Initialize a WebSocket specifying sub-protocols for the Sec-WebSocket-Protocol header, allowing server negotiation of the protocol to use. After connection, check `webSocket.protocol` for the negotiated protocol. ```objective-c #import // Initialize with supported sub-protocols NSArray *protocols = @[@"chat", @"superchat"]; SRWebSocket *webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:@"wss://chat.example.com/ws"] protocols: protocols]; webSocket.delegate = self; [webSocket open]; // After connection, check negotiated protocol // webSocket.protocol will contain the server-selected protocol (e.g., "chat") ``` -------------------------------- ### Handle WebSocket Connection Opened Event Source: https://context7.com/facebookincubator/socketrocket/llms.txt Implement `webSocketDidOpen:` to execute code once the WebSocket connection is successfully established. This is the point where you can safely send messages. ```Objective-C #import @interface MyViewController () @property (nonatomic, strong) SRWebSocket *webSocket; @end @implementation MyViewController - (void)webSocketDidOpen:(SRWebSocket *)webSocket { NSLog(@"WebSocket connection established"); // Connection is now open - safe to send messages [webSocket sendString:@"Hello from client!" error:nil]; // Check negotiated protocol if sub-protocols were requested if (webSocket.protocol) { NSLog(@"Negotiated protocol: %@", webSocket.protocol); } // Update UI on main thread dispatch_async(dispatch_get_main_queue(), ^{ self.statusLabel.text = @"Connected"; }); } @end ``` -------------------------------- ### Initialize SRWebSocket with Security Policy Source: https://context7.com/facebookincubator/socketrocket/llms.txt Initialize a WebSocket with a custom security policy for advanced TLS configuration and certificate validation. The default policy validates the certificate chain. ```objective-c #import // Create default security policy (validates certificate chain) SRSecurityPolicy *securityPolicy = [SRSecurityPolicy defaultPolicy]; // Initialize WebSocket with security policy NSURL *url = [NSURL URLWithString:@"wss://secure.example.com/socket"]; SRWebSocket *webSocket = [[SRWebSocket alloc] initWithURL:url securityPolicy:securityPolicy]; webSocket.delegate = self; [webSocket open]; // Or with URL request and protocols NSURLRequest *request = [NSURLRequest requestWithURL:url]; SRWebSocket *webSocket2 = [[SRWebSocket alloc] initWithURLRequest:request protocols: @[@"v1.protocol"] securityPolicy: securityPolicy]; ``` -------------------------------- ### Initialize SRWebSocket with NSURLRequest Source: https://context7.com/facebookincubator/socketrocket/llms.txt Initialize a WebSocket with a custom URL request for advanced configuration including custom headers, timeout intervals, and cache policies. ```objective-c #import // Create a mutable URL request with custom configuration NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"wss://api.example.com/socket"]]; [request setValue:@"Bearer your-token-here" forHTTPHeaderField:@"Authorization"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; request.timeoutInterval = 30.0; // Initialize WebSocket with the custom request SRWebSocket *webSocket = [[SRWebSocket alloc] initWithURLRequest:request]; webSocket.delegate = self; [webSocket open]; ``` -------------------------------- ### SRWebSocketDelegate Protocol Source: https://github.com/facebookincubator/socketrocket/blob/main/README.md Implement this protocol to handle WebSocket events such as connection opening, message reception, errors, and closure. ```objective-c @protocol SRWebSocketDelegate @optional - (void)webSocketDidOpen:(SRWebSocket *)webSocket; - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(NSString *)string; - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithData:(NSData *)data; - (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error; - (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(nullable NSString *)reason wasClean:(BOOL)wasClean; @end ``` -------------------------------- ### Handle WebSocket Connection Closure Source: https://context7.com/facebookincubator/socketrocket/llms.txt Implement this method to react to WebSocket connection closures, distinguishing between normal and abnormal terminations. This is essential for managing connection state and initiating reconnect attempts. ```Objective-C #import @implementation MyViewController - (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean { NSLog(@"WebSocket closed - Code: %ld, Reason: %@, Clean: %@", (long)code, reason ?: @"none", wasClean ? @"YES" : @"NO"); // Handle different closure codes switch (code) { case SRStatusCodeNormal: NSLog(@"Normal closure"); break; case SRStatusCodeGoingAway: NSLog(@"Server going away - will attempt reconnect"); [self scheduleReconnect]; break; case SRStatusCodeProtocolError: NSLog(@"Protocol error occurred"); break; case SRStatusCodeNoStatusReceived: NSLog(@"Connection closed without status"); break; default: NSLog(@"Closed with code: %ld", (long)code); break; } self.webSocket = nil; dispatch_async(dispatch_get_main_queue(), ^{ self.statusLabel.text = @"Disconnected"; }); } @end ``` -------------------------------- ### Observe WebSocket Ready State Changes with KVO Source: https://context7.com/facebookincubator/socketrocket/llms.txt Use Key-Value Observing (KVO) to monitor WebSocket connection state changes by observing the `readyState` property. Remember to remove the observer in `dealloc` to prevent memory leaks. ```Objective-C #import @implementation MyViewController - (void)setupWebSocket { self.webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:@"wss://example.com/socket"]]; self.webSocket.delegate = self; // Add KVO observer for readyState [self.webSocket addObserver:self forKeyPath:@"readyState" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; [self.webSocket open]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"readyState"]) { SRReadyState newState = [change[NSKeyValueChangeNewKey] integerValue]; switch (newState) { case SR_CONNECTING: NSLog(@"State: Connecting"); break; case SR_OPEN: NSLog(@"State: Open"); break; case SR_CLOSING: NSLog(@"State: Closing"); break; case SR_CLOSED: NSLog(@"State: Closed"); break; } } } - (void)dealloc { [self.webSocket removeObserver:self forKeyPath:@"readyState"]; } @end ``` -------------------------------- ### SRWebSocket Interface Source: https://github.com/facebookincubator/socketrocket/blob/main/README.md The SRWebSocket class provides methods for initializing, opening, closing, and sending data over a WebSocket connection. Set the delegate before opening the connection. ```objective-c @interface SRWebSocket : NSObject // Make it with this - (instancetype)initWithURLRequest:(NSURLRequest *)request; // Set this before opening @property (nonatomic, weak) id delegate; // Open with this - (void)open; // Close it with this - (void)close; // Send a Data - (void)sendData:(nullable NSData *)data error:(NSError **)error; // Send a UTF8 String - (void)sendString:(NSString *)string error:(NSError **)error; @end ``` -------------------------------- ### SRWebSocket Interface Source: https://github.com/facebookincubator/socketrocket/blob/main/README.md The main class for establishing and managing WebSocket connections. ```APIDOC ## SRWebSocket ### Description The Web Socket client class. ### Interface ```objective-c @interface SRWebSocket : NSObject // Initialize with a URL request - (instancetype)initWithURLRequest:(NSURLRequest *)request; // Set the delegate for receiving WebSocket events @property (nonatomic, weak) id delegate; // Open the WebSocket connection - (void)open; // Close the WebSocket connection - (void)close; // Send binary data over the WebSocket - (void)sendData:(nullable NSData *)data error:(NSError **)error; // Send a UTF8 string over the WebSocket - (void)sendString:(NSString *)string error:(NSError **)error; @end ``` ``` -------------------------------- ### SRWebSocketDelegate Protocol Source: https://github.com/facebookincubator/socketrocket/blob/main/README.md Protocol for handling WebSocket events and callbacks. ```APIDOC ## SRWebSocketDelegate ### Description Delegate protocol to handle WebSocket events. ### Methods - (void)webSocketDidOpen:(SRWebSocket *)webSocket; - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(NSString *)string; - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithData:(NSData *)data; - (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error; - (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(nullable NSString *)reason wasClean:(BOOL)wasClean; ### Notes - `webSocketDidOpen:` is called when the connection is successfully opened. - `didReceiveMessageWithString:` and `didReceiveMessageWithData:` are called when a message is received. - `didFailWithError:` is called when an error occurs. - `didCloseWithCode:` is called when the connection is closed. ``` -------------------------------- ### Objective-C Chat Manager with SocketRocket Source: https://context7.com/facebookincubator/socketrocket/llms.txt Manages WebSocket connections for a chat application, handling connection, disconnection, message sending, and delegate callbacks. Includes automatic reconnection with exponential backoff. ```Objective-C #import @interface ChatManager : NSObject @property (nonatomic, strong) SRWebSocket *webSocket; @property (nonatomic, assign) NSInteger reconnectAttempts; @property (nonatomic, strong) NSTimer *reconnectTimer; - (void)connect; - (void)disconnect; - (void)sendMessage:(NSString *)message; @end @implementation ChatManager - (void)connect { // Clean up existing connection self.webSocket.delegate = nil; [self.webSocket close]; // Create new WebSocket NSURL *url = [NSURL URLWithString:@"wss://chat.example.com/ws"]; self.webSocket = [[SRWebSocket alloc] initWithURL:url protocols:@["chat"]]; self.webSocket.delegate = self; NSLog(@"Connecting to WebSocket..."); [self.webSocket open]; } - (void)disconnect { [self.reconnectTimer invalidate]; self.reconnectTimer = nil; [self.webSocket closeWithCode:SRStatusCodeNormal reason:@"User disconnected"]; self.webSocket = nil; } - (void)sendMessage:(NSString *)message { if (self.webSocket.readyState != SR_OPEN) { NSLog(@"Cannot send - socket not open"); return; } NSDictionary *payload = @{ @"type": @"message", @"content": message, @"timestamp": @([[NSDate date] timeIntervalSince1970] * 1000) }; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:payload options:0 error:nil]; NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSError *error = nil; if (![self.webSocket sendString:jsonString error:&error]) { NSLog(@"Send failed: %@", error.localizedDescription); } } #pragma mark - SRWebSocketDelegate - (void)webSocketDidOpen:(SRWebSocket *)webSocket { NSLog(@"WebSocket connected"); self.reconnectAttempts = 0; // Send authentication message NSDictionary *auth = @{@"type": @"auth", @"token": @"user-token"}; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:auth options:0 error:nil]; [webSocket sendString:[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] error:nil]; } - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(NSString *)string { NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *message = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSString *type = message[@"type"]; if ([type isEqualToString:@"message"]) { [[NSNotificationCenter defaultCenter] postNotificationName:@"ChatMessageReceived" object:nil userInfo:message]; } } - (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error { NSLog(@"WebSocket failed: %@", error.localizedDescription); self.webSocket = nil; [self scheduleReconnect]; } - (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean { NSLog(@"WebSocket closed: %ld - %@", (long)code, reason); self.webSocket = nil; if (code != SRStatusCodeNormal) { [self scheduleReconnect]; } } - (void)scheduleReconnect { self.reconnectAttempts++; // Exponential backoff: 1s, 2s, 4s, 8s, max 30s NSTimeInterval delay = MIN(pow(2, self.reconnectAttempts - 1), 30); NSLog(@"Scheduling reconnect in %.0f seconds (attempt %ld)", delay, (long)self.reconnectAttempts); self.reconnectTimer = [NSTimer scheduledTimerWithTimeInterval:delay target:self selector:@selector(connect) userInfo:nil repeats:NO]; } @end ``` -------------------------------- ### Handle Incoming Binary Data Messages Source: https://context7.com/facebookincubator/socketrocket/llms.txt Process binary data received from the server using `webSocket:didReceiveMessageWithData:`. This is used for images, files, or custom binary formats. ```Objective-C #import @implementation MyViewController - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithData:(NSData *)data { NSLog(@"Received binary data: %lu bytes", (unsigned long)data.length); // Process received image data UIImage *receivedImage = [UIImage imageWithData:data]; if (receivedImage) { dispatch_async(dispatch_get_main_queue(), ^{ self.imageView.image = receivedImage; }); } // Or process as protocol buffer / custom binary format // MyProtocolMessage *message = [MyProtocolMessage parseFromData:data error:nil]; } // Optional: Control whether text frames are converted to strings - (BOOL)webSocketShouldConvertTextFrameToString:(SRWebSocket *)webSocket { // Return NO to receive text frames as NSData instead of NSString return YES; } @end ``` -------------------------------- ### Schedule WebSocket on Custom RunLoop Source: https://context7.com/facebookincubator/socketrocket/llms.txt Schedule the WebSocket on a specific run loop and mode for integration with custom threading models. Use `unscheduleFromRunLoop:forMode:` to remove it later. Access the default network run loop with `SR_networkRunLoop`. ```Objective-C #import SRWebSocket *webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:@"wss://example.com/socket"]]; webSocket.delegate = self; // Schedule on a specific run loop and mode NSRunLoop *customRunLoop = [NSRunLoop currentRunLoop]; // Or your custom run loop [webSocket scheduleInRunLoop:customRunLoop forMode:NSDefaultRunLoopMode]; // Later, if needed, unschedule from the run loop // [webSocket unscheduleFromRunLoop:customRunLoop forMode:NSDefaultRunLoopMode]; [webSocket open]; // Get the default network run loop used by SocketRocket NSRunLoop *networkRunLoop = [NSRunLoop SR_networkRunLoop]; ``` -------------------------------- ### Configure Delegate Dispatch Queue Source: https://context7.com/facebookincubator/socketrocket/llms.txt Set a custom dispatch queue or operation queue for delegate callbacks to avoid blocking the main thread. This is useful for managing concurrency and performance of your WebSocket operations. ```Objective-C #import // Create a serial queue for WebSocket callbacks dispatch_queue_t socketQueue = dispatch_queue_create(@"com.example.websocket", DISPATCH_QUEUE_SERIAL); SRWebSocket *webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:@"wss://example.com/socket"]]; webSocket.delegate = self; // Set custom dispatch queue for delegate callbacks webSocket.delegateDispatchQueue = socketQueue; [webSocket open]; // Alternatively, use an NSOperationQueue NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init]; operationQueue.name = @"WebSocket Callback Queue"; operationQueue.maxConcurrentOperationCount = 1; webSocket.delegateOperationQueue = operationQueue; ``` -------------------------------- ### Handle WebSocket Ping/Pong Messages Source: https://context7.com/facebookincubator/socketrocket/llms.txt Implement these methods to respond to ping frames from the server and process pong responses. SocketRocket automatically handles sending pong responses, but you can log latency and payload data. ```Objective-C #import @implementation MyViewController // Called when server sends a ping frame - (void)webSocket:(SRWebSocket *)webSocket didReceivePingWithData:(NSData *)data { NSLog(@"Received ping from server"); if (data) { NSString *pingMessage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"Ping payload: %@", pingMessage); } // SocketRocket automatically responds with a pong // No manual action required } // Called when we receive a pong in response to our ping - (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongData { NSLog(@"Received pong from server"); // Calculate round-trip time if you stored the ping timestamp NSTimeInterval latency = [[NSDate date] timeIntervalSinceDate:self.lastPingTime]; NSLog(@"Latency: %.2f ms", latency * 1000); if (pongData) { NSString *pongMessage = [[NSString alloc] initWithData:pongData encoding:NSUTF8StringEncoding]; NSLog(@"Pong payload: %@", pongMessage); } } @end ``` -------------------------------- ### Send Binary Data with SocketRocket Source: https://context7.com/facebookincubator/socketrocket/llms.txt Transmit binary data like images or files over a WebSocket connection. Use `sendDataNoCopy` for performance if the data buffer will not be modified. ```Objective-C #import // Send binary data NSData *imageData = UIImagePNGRepresentation(myImage); NSError *error = nil; BOOL success = [webSocket sendData:imageData error:&error]; if (!success) { NSLog(@"Failed to send data: %@", error.localizedDescription); } // Send binary data without making a defensive copy (for performance) // Use only if you're certain the data won't be modified after this call NSMutableData *largeData = [NSMutableData dataWithLength:1024 * 1024]; // ... populate largeData ... [webSocket sendDataNoCopy:largeData error:&error]; ``` -------------------------------- ### Handle WebSocket Errors Source: https://context7.com/facebookincubator/socketrocket/llms.txt Implement this method to gracefully handle connection failures and various error conditions, including specific HTTP status codes and SSL/TLS issues. It's crucial for implementing reconnection logic. ```Objective-C #import @implementation MyViewController - (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error { NSLog(@"WebSocket failed with error: %@", error.localizedDescription); // Check for specific error conditions if ([error.domain isEqualToString:SRWebSocketErrorDomain]) { // Check HTTP response code if available NSNumber *httpCode = error.userInfo[SRHTTPResponseErrorKey]; if (httpCode) { NSLog(@"HTTP Status Code: %@", httpCode); } } // Handle SSL/TLS errors if ([error.domain isEqualToString:NSURLErrorDomain]) { if (error.code == NSURLErrorClientCertificateRejected) { NSLog(@"SSL Certificate validation failed"); } else if (error.code == NSURLErrorTimedOut) { NSLog(@"Connection timed out"); } } // Clean up and potentially reconnect self.webSocket = nil; dispatch_async(dispatch_get_main_queue(), ^{ self.statusLabel.text = @"Connection Failed"; // Implement reconnection logic with exponential backoff [self scheduleReconnect]; }); } @end ``` -------------------------------- ### Handle Incoming String Messages Source: https://context7.com/facebookincubator/socketrocket/llms.txt Process text messages received from the server using `webSocket:didReceiveMessageWithString:`. This method is suitable for JSON or plain text data. ```Objective-C #import @implementation MyViewController - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(NSString *)string { NSLog(@"Received message: %@", string); // Parse JSON message NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; NSError *error = nil; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; if (json) { NSString *type = json[@"type"]; if ([type isEqualToString:@"chat"]) { NSString *message = json[@"message"]; NSString *sender = json[@"sender"]; [self displayChatMessage:message fromSender:sender]; } } // Update UI on main thread dispatch_async(dispatch_get_main_queue(), ^{ [self.messages addObject:string]; [self.tableView reloadData]; }); } @end ``` -------------------------------- ### Send Ping Messages with SocketRocket Source: https://context7.com/facebookincubator/socketrocket/llms.txt Send ping frames to maintain the connection or check latency. A payload can be included for custom identification. ```Objective-C #import // Send ping without payload NSError *error = nil; [webSocket sendPing:nil error:&error]; // Send ping with custom payload data NSData *pingPayload = [@"ping-identifier-123" dataUsingEncoding:NSUTF8StringEncoding]; [webSocket sendPing:pingPayload error:&error]; if (error) { NSLog(@"Failed to send ping: %@", error.localizedDescription); } ``` -------------------------------- ### Close WebSocket Connection with SocketRocket Source: https://context7.com/facebookincubator/socketrocket/llms.txt Gracefully close the WebSocket connection. Supports custom status codes and reasons for closure, such as user logout or app backgrounding. ```Objective-C #import // Close with default normal closure (code 1000) [webSocket close]; // Close with custom code and reason [webSocket closeWithCode:SRStatusCodeNormal reason:@"User logged out"]; // Close with going away status (e.g., app entering background) [webSocket closeWithCode:SRStatusCodeGoingAway reason:@"App entering background"]; // Available status codes: // SRStatusCodeNormal = 1000 - Normal closure // SRStatusCodeGoingAway = 1001 - Endpoint going away // SRStatusCodeProtocolError = 1002 - Protocol error // SRStatusCodeUnhandledType = 1003 - Received unhandled data type ``` -------------------------------- ### Send String Messages via SRWebSocket Source: https://context7.com/facebookincubator/socketrocket/llms.txt Send UTF-8 encoded string messages to the WebSocket server. The `sendString:error:` method returns a boolean indicating success and provides error information if it fails. ```objective-c #import // Send a simple text message NSError *error = nil; BOOL success = [webSocket sendString:@"Hello, Server!" error:&error]; if (!success) { NSLog(@"Failed to send message: %@", error.localizedDescription); } // Send JSON data as string NSDictionary *message = @{ @"type": @"message", @"content": @"Hello World", @"timestamp": @([[NSDate date] timeIntervalSince1970]) }; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:message options:0 error:nil]; NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; [webSocket sendString:jsonString error:&error]; ``` -------------------------------- ### Set Request Cookies for WebSocket Handshake Source: https://context7.com/facebookincubator/socketrocket/llms.txt Configure cookies to be sent with the WebSocket handshake request by setting the `requestCookies` property before opening the connection. Ensure cookies are properly formatted as `NSHTTPCookie` objects. ```Objective-C #import SRWebSocket *webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:@"wss://example.com/socket"]]; webSocket.delegate = self; // Create cookies to send with the connection NSHTTPCookie *sessionCookie = [NSHTTPCookie cookieWithProperties:@{ NSHTTPCookieName: @"session_id", NSHTTPCookieValue: @"abc123xyz", NSHTTPCookieDomain: @"example.com", NSHTTPCookiePath: @"/" }]; NSHTTPCookie *authCookie = [NSHTTPCookie cookieWithProperties:@{ NSHTTPCookieName: @"auth_token", NSHTTPCookieValue: @"your-auth-token", NSHTTPCookieDomain: @"example.com", NSHTTPCookiePath: @"/", NSHTTPCookieSecure: @YES }]; // Set cookies before opening the connection webSocket.requestCookies = @[sessionCookie, authCookie]; [webSocket open]; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.