WebSocket之SocketRocket使用

Facebook的开源WebSocket框架

pod导入

pod 'SocketRocket'

使用方法

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"ws://121.40.165.18:8800"]];
request.timeoutInterval = 15.0;
_socket = [[SRWebSocket alloc] initWithURLRequest:request];
_socket.delegate = self;
[_socket open];

实现SRWebSocket代理SRWebSocketDelegate

// message will either be an NSString if the server is using text
// or NSData if the server is using binary.
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message;

@optional

- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;

// Return YES to convert messages sent as Text to an NSString. Return NO to skip NSData -> NSString conversion for Text messages. Defaults to YES.
- (BOOL)webSocketShouldConvertTextFrameToString:(SRWebSocket *)webSocket;

// SRWebSockets are intended for one-time-use only. Open should be called once and only once.
- (void)open;

open方法只能调用一次,多次调用会崩溃,断开连接重新开启时需要重新初始化一个SRWebSocket对象

你可能感兴趣的:(WebSocket之SocketRocket使用)