Bootstrap

IOS GCDAsyncUdpSocket GCDAsyncSocket

https://www.jianshu.com/p/99042ac1aa5f


1、GCDAsyncUdpSocket

#import "GCDAsyncUdpSocket.h"遵守协议<GCDAsyncUdpSocketDelegate>声明一个属性@property (strong, nonatomic)GCDAsyncUdpSocket * udpSocket;

创建Socket
_udpSocket = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
监听接口&接收数据[1]
    NSError * error = nil;
    [_udpSocket bindToPort:udpPort error:&error];
    if (error) {//监听错误打印错误信息
        NSLog(@"error:%@",error);
    }else {//监听成功则开始接收信息
        [_udpSocket beginReceiving:&error];
    }
udp不用连接,故直接发送数据
[_udpSocket sendData:sendData toHost:ipAddress port:udpPort withTimeout:-1 tag:0];

对于toHost的参数ipAddress我说明一下,NSString * ipAddress = [self deviceIPAdress];[self deviceIPAdress]方法就是获取ip地址,具体可参见我另一篇文章《获取iOS设备信息(内存/电量/容量/型号/IP地址)

看看发送数据结果://此为GCDAsyncUdpSocket代理方法
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
    NSLog(@"发送信息成功");
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error
{
    NSLog(@"发送信息失败");
}
发送成功就该接收数据了://此为GCDAsyncUdpSocket代理方法
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
{
    NSLog(@"接收到%@的消息:%@",address,data);//自行转换格式吧
}

2、GCDAsyncSocket
头文件#import "GCDAsyncSocket.h",代理GCDAsyncSocketDelegate
属性:@property (strong, nonatomic) GCDAsyncSocket *clientSocket;
初始化:
_clientSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

请求连接,发送数据:

    [self.clientSocket disconnect];
    NSError *err = nil;
    if (![_clientSocket connectToHost:@"192.168.0.104" onPort:8888 error:&err])
    {
        NSLog(@"error:%@",err);
        return;
    }
    NSString *string = @"=================== send socket test ===================";
    NSData *sendData = [string dataUsingEncoding:NSUTF8StringEncoding];
    [_clientSocket writeData:sendData withTimeout:-1 tag:1];
    [_clientSocket readDataWithTimeout:-1 tag:0]; //一直排队读取读栈内容,直到socket断开

接收数据,代理方法:

// socket成功连接回调
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    NSLog(@"成功连接到%@:%d",host,port);
    self.textView.text = [self.textView.text stringByAppendingFormat:@"成功连接到%@:%d\r\n",host,port];
    [_clientSocket readDataWithTimeout:-1 tag:99];
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSString* obtainContent = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@\r\n",obtainContent);
    self.textView.text = [self.textView.text stringByAppendingFormat:@"%@\r\n",obtainContent];
    [_clientSocket readDataWithTimeout:-1 tag:0]; //一直排队读取读栈内容,直到socket断开
}


;