代码日志《ios Websocket》

567 阅读1分钟

666的库

iOS websocket对接,OC中有优秀的SocketRocket,swift中有优秀的Starscream,实现方式也是很简单,可以根据官方文档现实。

SocketRocket是使用NSInputStream 和 NSOutputStream,但是Starscream是做了系统版本判断,采用的方式有多种,作者还是很严谨的

image.png iOS12.0 是使用NWConnection而在 iOS13.0 后是直接使用URLSessionWebSocketTask

URLSessionWebSocketTask的使用

@property(nonatomic, strong) NSURLSessionWebSocketTask *task;
NSString *urlstr = @"ws://192.168.126.65:8001";

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];

NSURL *url = [NSURL URLWithString:[urlstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:[NSOperationQueue mainQueue]];

self.task = [session webSocketTaskWithRequest:[NSURLRequest requestWithURL:url]];
self.task.delegate = self;
[self.task resume];
[self getMessage];
- (void)getMessage {

    __weak typeof(self) weakself = self;

    [self.task receiveMessageWithCompletionHandler:^(NSURLSessionWebSocketMessage *_Nullable message, NSError *_Nullable error) {

        dispatch_async(dispatch_get_global_queue(0, 0), ^{

        __strong typeof(weakself) ss = weakself;

        if (message.data && !error) {
                NSDictionary *info = [NSJSONSerialization JSONObjectWithData:message.data options:NSJSONReadingFragmentsAllowed error:nil];
                NSLog(@"获取信息:%@",info);
            }

        });

      [weakself getMessage];
    }];

}

- (void)URLSession:(NSURLSession *)session webSocketTask:(NSURLSessionWebSocketTask *)webSocketTask didOpenWithProtocol:(nullable NSString *) protocol {
    NSLog(@"连接成功");
}

- (void)URLSession:(NSURLSession *)session webSocketTask:(NSURLSessionWebSocketTask *)webSocketTask didCloseWithCode:(NSURLSessionWebSocketCloseCode)closeCode reason:(nullable NSData *)reason {
    NSLog(@"连接断开");
}