iOS GCDAsyncUdpSocket UDP 建立连接,实现组播

iOS GCDAsyncUdpSocket UDP 建立连接,实现组播

导入框架 #import “GCDAsyncUdpSocket.h”,
接收代理 @interface RootViewController : UIViewController< GCDAsyncUdpSocketDelegate>

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSendUDPSocket];
    [self initReceiveUDPSocket];
    }
// 初始化发送 UDP socket 
-(void)initSendUDPSocket{
    self.sendUDPSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    NSError * error = nil;
    [self.sendUDPSocket bindToPort:8888 error:&error];// bindToPort:是服务器的port
    if (error) {    //监听错误打印错误信息
        NSLog(@"error:%@",error);
    }else {         //监听成功则开始接收信息
        [self.sendUDPSocket enableBroadcast:YES error:nil];   // !!!!!!开启组播
        if (error) {
            NSLog(@"开启组播失败: %@",error);
        }
        [self sendUDPData:@"DDC"];
    }
}
// 初始化接收 UDP socket( 从另外一个 port 返回数据)
-(void)initReceiveUDPSocket{
    self.receiveUDPSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    NSError * error = nil;
    [self.receiveUDPSocket bindToPort:8899 error:&error];
    if (error) {    //监听错误打印错误信息
        NSLog(@"error:%@",error);
    }else {         //监听成功则开始接收信息
        [self.receiveUDPSocket beginReceiving:&error];// 一直接收
        // [self.receiveUDPSocket receiveOnce:&error]; (只接收一次)

    }
}
// 发送UDP
-(void)sendUDPData:(NSString *)str
{
    NSLog(@"to ddc : %@",str);
    NSData *data =[str dataUsingEncoding:NSUTF8StringEncoding];
    [self.sendUDPSocket sendData:data toHost:@"255.255.255.255" port:8888 withTimeout:-1 tag:0];   // 注意:这里的发送也是异步的,"255.255.255.255",是组播方式,withTimeout设置成-1代表超时时间为-1,即永不超时; 
}  
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
    NSLog(@"发送信息成功");
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error
{
    NSLog(@"发送信息失败");
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
{
    NSString *aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"接收到消息: %@",aStr);
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值