开源网络库 GCDAsyncSocket 笔记

GCDAsyncSocket 地址: https://github.com/robbiehanson/CocoaAsyncSocket/

 

使用方法:

创建:

asyncsocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

这里我们让所有的回调执行都发生在主线程的queue里,当然我们可以传一个专用的queue.

连接 :

NSError *err = nil;
if (![asyncsocket connectToHost:@"deusty.com" onPort:80 error:&err]) // Asynchronous!
{
    //该方法异步,返回错误是因为 delegate没设置等
    NSLog(@"I goofed: %@", err);
}

 该方法会立刻返回,当成功连接上,delegate 的 socket:didConnectToHost:port: 方法会被调用.

- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"Cool, I'm connected! That was easy.");
}

有几种不同的连接方法,比如带超时的.。。。

虽然这个时候可能 socket 还没连接上,但是我们依然可以投递 读/写 请求:

[asyncSocket readDataToLength:LENGTH_HEADER withTimeout:-1 tag:TAG_HEADER];

这样读请求会自动进入了队列,当socket 连接上后,请求会自动出队被执行。(这里假设先读一个包头,再根据长度接收包体,这个读操作完成后 socket:didReadData:withTag: 会被调用)

当然我们可以投递多个读写操作而不必等待上一个完成.

[asyncSocket writeData:msgHeader withTimeout:-1 tag:TAG_HEADER];
[asyncSocket writeData:msgBody withTimeout:-1 tag:TAG_BODY];

上面的操作均为异步。下面为操作完成的委托方法:

read:

- (void)socket:(GCDAsyncSocket *)sender didReadData:(NSData *)data withTag:(long)tag
{
    if (tag == TAG_HEADER)
    {
        int bodyLength = [self parseHeader:data];
        [socket readDataToLength:bodyLength withTimeout:-1 tag:TAG_RESPONSE_BODY];
    }
    else if (tag == TAG_RESPONSE_BODY)
    {
        // Process the response
        [self handleResponseBody:data];

        // Start reading the next response
        [socket readDataToLength:headerLength withTimeout:-1 tag:TAG_FIXED_LENGTH_HEADER];
    }
}
//还有另一个读方法,
// [asyncSocket readDataToData:msgSeparator withTimeout:TIMEOUT_NONE tag:TAG_CAPABILITIES];
// 读当遇到一个指定的分隔符后操作返回。比如用作 http, 因为http 每个消息都会有一个@"\r\n\r\n" 结尾标志.
//如果想跟踪进度 socket: didReadPartialDataOfLength: tag: 用这个

write:

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    if (tag ==TAG_HEADER) 
    NSLog(@"TAG_HEADER request sent"); 
  else if (tag ==TAG_BODY) 
    NSLog(@"TAG_BODY request sent");
}

断开释放一个连接实例

[asyncSocket setDelegate:nil delegateQueue:NULL];
[asyncSocket disconnect];
[asyncSocket release];

  

相关的delegate 方法(回调)

socket: didConnectToHost: port:

socket: didReadData: withTag:
socket: didReadPartialDataOfLength: tag:
socket: shouldTimeoutReadWithTag: elapsed: bytesDone:

socket: didWriteDataWithTag:
socket: didWritePartialDataOfLength: tag:
socket: shouldTimeoutWriteWithTag: elapsed: bytesDone:

socketDidSecure:

socket: didAcceptNewSocket:

newSocketQueueForConnectionFromAddress: onSocket:

socketDidCloseReadStream:

socketDidDisconnect: withError:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值