完整的错误描述为:
Domain=NSPOSIXErrorDomain Code=13 "Permission denied" UserInfo={NSLocalizedDescription=Permission denied, NSLocalizedFailureReason=Error in send() function.}
原始代码是这样的:
clientBroadcastSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:queue socketQueue:nil];
[clientBroadcastSocket enableBroadcast:YES error:nil];
[clientBroadcastSocket bindToPort:BROADCASTPORT error:nil];
NSLog(@"发送中的广播 localPort:%@", @(clientBroadcastSocket.localPort));
[clientBroadcastSocket sendData:data toHost:BROADCASTHOST port:BROADCASTPORT withTimeout:10 tag:100];
看似没有什么错误开启了广播也绑定了端口。
实际上,绑定端口需要放在开启广播之前,即需要先 bindToPort 再 enableBroadcast。
修改后的代码:
clientBroadcastSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:queue socketQueue:nil];
// enableBroadcast 要放在 bindToPort 后才可以
[clientBroadcastSocket bindToPort:BROADCASTPORT error:nil];
[clientBroadcastSocket enableBroadcast:YES error:nil];
NSLog(@"发送中的广播 localPort:%@", @(clientBroadcastSocket.localPort));
[clientBroadcastSocket sendData:data toHost:BROADCASTHOST port:BROADCASTPORT withTimeout:10 tag:100];