iOS UDP组播

2019-11-27  本文已影响0人  当优秀成为习惯

组播步骤:

代码实现

    // 创建udpsocket对象
   GCDAsyncUdpSocket *udpServer = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)];
    self.recvSocket= udpServer;    
    NSError *error = nil;
    // 绑定端口
    [udpServer bindToPort:50091 error:&error];
    NSLog(@"绑定端口 %@", error);
    // 开启广播
    [udpServer enableBroadcast:YES error:&error];
    NSLog(@"开启广播: %@", error);
  // 加入组播
    [udpServer joinMulticastGroup:@"239.100.100.1" error:&error];
    NSLog(@"加入组播组: %@", error);
// 开始接收组播数据,会回掉一下代理方法
    [udpServer beginReceiving:&error];
    NSLog(@"Error starting server (recv): %@", error);
接收数据的代理方法
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
                                             fromAddress:(NSData *)address
withFilterContext:(nullable id)filterContext{
    NSMutableData *dt = [NSMutableData dataWithData:data];
    NSData *rDt = [dt subdataWithRange:NSMakeRange(2, data.length-6)];
    NSString *str = [[NSString alloc] initWithData:rDt encoding:NSUTF8StringEncoding];
    NSLog(@"data:%@",str);
    LogFunc;
}
控制器销毁要关闭退出组播,不然下次进来会报错,因为不能重复加入
- (void)dealloc{
    [self.recvSocket leaveMulticastGroup:@"239.100.100.1" error:nil];
    [self.recvSocket close];
}
上一篇下一篇

猜你喜欢

热点阅读