当前位置: 代码迷 >> 综合 >> iOS app 实现UDP通信
  详细解决方案

iOS app 实现UDP通信

热度:25   发布时间:2024-01-21 19:39:04.0

使用CocoaAsyncSocket第三方库完成

GCDAsyncUdpSocket *udpSocket; // 定义一个socket的对象
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];NSError *error = nil;// 绑定端口[udpSocket bindToPort:8888 error:&error];// 启用广播[udpSocket enableBroadcast:YES error:&error];if (error) {[SVProgressHUD showErrorWithStatus:@"启用失败"];}else {NSLog(@"%@", [udpSocket localHost]);// 开始接收消息[udpSocket beginReceiving:&error];}

设置代理方法

#pragma mark - GCDAsyncUdpSocketDelegate
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(nullable id)filterContext {NSLog(@"success");NSString *ip = [GCDAsyncUdpSocket hostFromAddress:address];NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];NSLog(@"收到 %@ %@", ip, s);[sock receiveOnce:nil];dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{uint16_t port = 9999;[self sendBackToHost:ip port:port withMessage:s];});
}
- (void)sendBackToHost:(NSString *)ip port:(uint16_t)port withMessage:(NSString *)s{// 回一个 hello summerxx toochar *s = "hello" ;NSData *data = [NSData dataWithBytes:str length:strlen(s)];[udpSocket sendData:data toHost:ip port:port withTimeout:0.1 tag:200];
}

 

  相关解决方案