Bootstrap

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);
}
;