cha*_*yWu 5 udp objective-c broadcast ios gcdasyncsocket
我正在使用GCDAsyncUdpSocket在我的应用程序中编写UDP套接字.场景是这样的:当用户点击按钮时,它将在LAN中发送广播数据包然后收听响应,LAN中有一个服务器将响应一个UDP数据包.当应用收到响应时,它会执行某些操作.
我设定GCDAsyncUdpSocket如下:
- (void)setupSocket
{
_udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![_udpSocket bindToPort:18686 error:&error]) {
NSLog(@"Error binding: %@",error);
return;
}
if (![_udpSocket beginReceiving:&error]) {
NSLog(@"Error receiving: %@",error);
return;
}
if (![_udpSocket enableBroadcast:YES error:&error]) {
NSLog(@"Error enableBroadcast: %@",error);
return;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我按钮按钮动作发送如下:
NSString *host = @"255.255.255.255";
int port = 8585;
NSString *msg = @"Hello from iOS";
NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];
[_udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:0];
Run Code Online (Sandbox Code Playgroud)
在
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
Run Code Online (Sandbox Code Playgroud)
方法我听端口做事.它在开始时工作正常,但如果您稍后尝试单击该按钮(约1小时),则它不能再发送UDP数据包.
我在LAN中的服务器将打印收到的数据.我觉得send方法有问题.所以我使用BSD套接字方法发送数据.并用于GCDAsyncUdpSocket接收回复.但过了一会儿就发生了同样的事情.这次我可以发送但无法接收.
我错过了什么GCDAsyncUdpSocket吗?为什么一段时间后不能发送/接收?任何帮助将非常感激.
| 归档时间: |
|
| 查看次数: |
1721 次 |
| 最近记录: |