GCDAsyncSocket的使用

什么是GCDAsyncSocket

GCDAsyncSocket 是用于 OS X 和 iOS 上的异步 Socket 网络通讯包。提供了易用而且功能强大的异步套接字开发库
https://github.com/robbiehanson/CocoaAsyncSocket

基本使用

dispatch_queue_t queue = dispatch_queue_create("com.test.testsocket.setter", DISPATCH_QUEUE_SERIAL);
_socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:queue socketQueue:nil];

上面这两部就做好了初始化的操作,而且要注意,socket在整个项目中都会用到,所以要做成单例抽取出来

由于苹果要求对ipv6做支持,所以还需要加上这段代码:

_socket.IPv4PreferredOverIPv6 = NO; // 设置支持IPV6

到此准备工作就做好啦。

连接socket

NSError *error = nil;

[self.socket connectToHost:@"你的域名" onPort:@"你的端口" withTimeout:@"超时时间" error:&error];

如果连接成功,我们会收到socket连接成功的回调,我们可以在这里做心跳的处理,或者token的验证等:

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port

如果连接失败,我们会收到失败的回调,可以失败里面做重连的操作

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
读和写

socket连接建立了,这个时候我们需要和后台约定好协议格式进行通信,比如我们可以长度+真实数据的格式进行通信

    // 将messageDict进行序列化(这里也可以使用kryo进行序列化,详情见http://www.jianshu.com/p/43f2a39ce1fd)NSData *contents = [NSJSONSerialization dataWithJSONObject:messageDict options:NSJSONWritingPrettyPrinted error:&error];
    if(error)
    {
        MyLog(@"%s--------error:%@",__func__,error);
    }
    // 获取长度int len = (int)contents.length;

    NSData *lengthData = [NSData dataWithBytes:&len length:sizeof(len)];
    // 发送长度
    [self.socket writeData:lengthData withTimeout:-1 tag:0];
    // 发送真实数据
    [self.socket writeData:contents withTimeout:-1 tag:0];
    // 读取数据
    [self.socket readDataWithTimeout:-1 tag:0];

我们在向服务器写完数据之后一定不要忘了调用读方法,这样才能收到从服务器那边返回的数据,并且会收到读的回调

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag

在这个回调里面,我们可以用一个缓冲区来不断接收我们收到的数据,并且在收到完整的数据后进行相应的处理

断开socket连接

[self.socket disconnect];

这样子,socket的基本通信就告一段落啦


转载自微信号【IT牛料】


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用GCDAsyncSocket接收esp32发送的数据的示例代码: 1. 首先需要导入GCDAsyncSocket库 ```objc #import "GCDAsyncSocket.h" ``` 2. 创建一个GCDAsyncSocket实例,并设置代理 ```objc GCDAsyncSocket *socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()]; ``` 3. 在连接到esp32时,调用connectToHost方法 ```objc NSError *error = nil; if (![socket connectToHost:host onPort:port error:&error]) { NSLog(@"Error connecting: %@", error); } ``` 其中,host为esp32的IP地址,port为esp32服务器开放的端口号。 4. 实现GCDAsyncSocketDelegate中的方法,处理接收到的数据 ```objc - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag { // 处理接收到的数据 NSString *receivedData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"Received data: %@", receivedData); // 继续监听数据 [sock readDataWithTimeout:-1 tag:0]; } ``` 在didReadData方法中,可以处理接收到的数据。然后,通过调用readDataWithTimeout方法,继续监听数据。 完整示例代码如下: ```objc #import "ViewController.h" #import "GCDAsyncSocket.h" @interface ViewController () <GCDAsyncSocketDelegate> @property (nonatomic, strong) GCDAsyncSocket *socket; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 创建socket实例 self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()]; // 连接esp32 NSString *host = @"esp32的IP地址"; uint16_t port = 8080; NSError *error = nil; if (![self.socket connectToHost:host onPort:port error:&error]) { NSLog(@"Error connecting: %@", error); } } #pragma mark - GCDAsyncSocketDelegate - (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port { NSLog(@"Connected to host %@:%d", host, port); // 开始监听数据 [sock readDataWithTimeout:-1 tag:0]; } - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag { // 处理接收到的数据 NSString *receivedData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"Received data: %@", receivedData); // 继续监听数据 [sock readDataWithTimeout:-1 tag:0]; } - (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err { NSLog(@"Disconnected from host"); } @end ``` 注意,以上代码中的host和port需要替换成实际的esp32的IP地址和端口号。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值