Quick Start
This guide will help you establish your first WebSocket connection using SocketRocket.
Prerequisites
Ensure you have installed the library via CocoaPods, Carthage, or manual integration.
Basic Connection
To open a connection, you initialize an SRWebSocket instance with a URL and call open. You must retain the web socket object yourself.
#import <SocketRocket/SocketRocket.h>
@interface MyWebSocketController : NSObject <SRWebSocketDelegate>
@property (nonatomic, strong) SRWebSocket *webSocket;
@end
@implementation MyWebSocketController
- (void)connect {
// 1. Create the request
NSURL *url = [NSURL URLWithString:@"ws://localhost:9000/chat"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2. Initialize the socket
self.webSocket = [[SRWebSocket alloc] initWithURLRequest:request];
// 3. Set the delegate to receive events
self.webSocket.delegate = self;
// 4. Open the connection
[self.webSocket open];
}
// MARK: - SRWebSocketDelegate
- (void)webSocketDidOpen:(SRWebSocket *)webSocket {
NSLog(@"Websocket Connected");
// Send a message once connected
[webSocket sendString:@"Hello World!"];
}
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
NSLog(@"Received message: %@", message);
}
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
NSLog(@"Websocket Failed With Error: %@", error);
self.webSocket = nil;
}
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean {
NSLog(@"Websocket closed");
self.webSocket = nil;
}
@end
Lifecycle Note
An SRWebSocket instance is intended for one-time use only. If the socket closes (either via error or normal closure), you cannot reuse the instance. You must create a new SRWebSocket object to reconnect.