我相信上面的评论是正确的,你没有在 init 上正确设置 Delegate。套接字创建应该是这样的
GCDAsyncUdpSocket* udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![udpSocket bindToPort:0 error:&error])
{
[self logError:[NSString stringWithFormat:@"Error binding: %@", error]];
return;
}
if (![udpSocket beginReceiving:&error])
{
[self logError:[NSString stringWithFormat:@"Error receiving: %@", error]];
return;
}
NSString *_host = nil;
uint16_t _port = 0;
[GCDAsyncUdpSocket getHost:&_host port:&_port fromAddress:udpSocket.localAddress];
[self logInfo:[NSString stringWithFormat:@"Socket setup on host %@:%d", _host, _port]];
[self logInfo:@"Socket created successfully."];
除非您使用的 GCDAsyncUdpSocket 版本与我熟悉的不同,否则正确的回调方法实际上是下面的方法。当设置了委托并且在正确的端口上接收到数据包时,它会自动调用。
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext