GCDAsyncUdpSocket的简单使用

来源:互联网 发布:数组 push pop 编辑:程序博客网 时间:2024/06/08 02:07

说明:只是对GCDAsyncUdpSocket进行简单的使用,实现消息的收发。

1.导入

#import "GCDAsyncUdpSocket.h"

2.创建全局变量

//这个socket用来做发送使用当然也可以接收

GCDAsyncUdpSocket *sendUdpSocket;

3.创建单例

static UDPManage *myUDPManage =nil;


+(instancetype)shareUDPManage{

    staticdispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        myUDPManage = [[UDPManagealloc]init];

        [myUDPManagecreateClientUdpSocket];

    });

    returnmyUDPManage;

}

4.创建socket

#pragma mark -- 创建socket

-(void)createClientUdpSocket{

    //1.创建一个 udp socket用来和服务器端进行通讯

    sendUdpSocket = [[GCDAsyncUdpSocketalloc] initWithDelegate:selfdelegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)];

    //2.banding一个端口(可选),如果不绑定端口,那么就会随机产生一个随机的电脑唯一的端口

    //端口数字范围(1024,2^16-1)

    NSError * error =nil;

    [sendUdpSocketbindToPort:8085error:&error];

    //启用广播

    [sendUdpSocketenableBroadcast:YESerror:&error];

    if (error) {//监听错误打印错误信息

        NSLog(@"error:%@",error);

    }else {//监听成功则开始接收信息

        [sendUdpSocketbeginReceiving:&error];

    }


}

5.发送消息

-(void)startScan{

    

    NSString *s =@"mapleTest";

    NSData *data = [sdataUsingEncoding:NSUTF8StringEncoding];

    NSString *host =@"255.255.255.255";//此处如果写成固定的IP就是对特定的server监测;我这种写法是为了多方监测

    uint16_t port =36877;//通过端口监测

    [sendUdpSocketsendData:data toHost:hostport:port withTimeout:-1tag:100];

}

6.相关的代理

#pragma mark -GCDAsyncUdpSocketDelegate

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag{

    if (tag ==100) {

        //NSLog(@"表示标记为100的数据发送完成了");

    }

}


-(void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{

    NSLog(@"标记为tag %ld的发送失败失败原因 %@",tag, error);

}


-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{

    

    NSString *ip = [GCDAsyncUdpSockethostFromAddress:address];

    uint16_t port = [GCDAsyncUdpSocketportFromAddress:address];

    NSString *s = [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];

    // 继续来等待接收下一次消息

    NSLog(@"收到服务端的响应 [%@:%d] %@", ip, port, s);

    [sock receiveOnce:nil];

    //此处根据实际和硬件商定的需求决定是否主动回一条消息

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 *NSEC_PER_SEC)),dispatch_get_main_queue(), ^{

        [selfsendBackToHost:ip port:port withMessage:s];

    });

}


- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error

{

    NSLog(@"udpSocket关闭");

}


-(void)sendBackToHost:(NSString *)ip port:(uint16_t)port withMessage:(NSString *)s{

    NSString *msg =@"我收到了";

    NSData *data = [msgdataUsingEncoding:NSUTF8StringEncoding];

    [sendUdpSocketsendData:data toHost:ipport:port withTimeout:0.1tag:200];

    

}


0 0
原创粉丝点击