0.准备
pod 'SocketRocket'
#import "SRWebSocket.h"
@interface LongConnect ()<SRWebSocketDelegate>
1.创建
NSString *urlStr = [NSString stringWithFormat:@"ws://192.168.1.112:8080/dev/echo/?username=%@&companyname=%@", [df objectForKey:@"username"], [df objectForKey:@"companyname"]];
self.webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
// 遵守SRWebSocketDelegate协议
self.webSocket.delegate = self;
// 打开
[self.webSocket open];
2.关闭
// 销毁长链接
// 关闭之后不可以再open,必须重新创建一个新的连接对象
[self.webSocket close];
2. SRWebSocketDelegate协议实现
// 1. 已经打开连接
- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
// 2. 失败
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
//3. 接收数据
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message{
NSLog(@"%@", message);
// 如果接收的是Jons字符串,可以转字典。如果是一对多接收,可以使用广播
NSDictionary *dic = [NSString parseJSONStringToNSDictionary:message];
[self.notificationCenter postNotificationName:@"长链接数据" object:nil userInfo:dic];
}
网友评论