GCDAsyncUdpSocket,“无法绑定不止一次套接字”
问题描述:
我正在使用GCDAsyncUdpSocket在iphone和远程udp服务器之间获得udp广播。 我在特定的端口上发送一个小的“hello”到“255.255.255.255”广播地址。GCDAsyncUdpSocket,“无法绑定不止一次套接字”
然后服务器回复,允许我发现它的IP地址。
一切工作正常,尤其是使用模拟器,除非如果我在iphone上运行一次,当我试图停止应用程序并立即运行后,我得到一个“不能绑定套接字多次”错误。当我点击xcode中的停止或当我在IOS中杀死应用程序时,会发生这种情况。
这里是我的代码示例:
#import "GCDAsyncUdpSocket.h"
- (void)viewDidLoad
{
[super viewDidLoad];
if (udpSocket == nil)
{
[self setupSocket];
}
}
- (void)setupSocket
{
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
[udpSocket enableBroadcast:YES error:nil];
NSData *data = [@"hello" dataUsingEncoding:NSUTF8StringEncoding];
[udpSocket sendData:data toHost:@"255.255.255.255" port:21180 withTimeout:-1 tag:tag++];
NSError *error = nil;
if (![udpSocket bindToPort:0 error:&error])
{
[self logError:FORMAT(@"Error binding: %@", error)];
return;
}
if (![udpSocket beginReceiving:&error])
{
[self logError:FORMAT(@"Error receiving: %@", error)];
return;
}
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (msg)
{
[self logMessage:FORMAT(@"RECV: %@", msg)];
}
else
{
NSString *host = nil;
uint16_t port = 0;
[GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];
[self logInfo:FORMAT(@"RECV: Unknown message from: %@:%hu", host, port)];
}
[udpSocket close];
udpSocket = NIL;
}
事实上,它似乎插座引用仍然绑定,忽略关闭动作,并设置为零。
欢迎任何建议, 感谢您的阅读。
FKY
也许这有助于:http://stackoverflow.com/questions/16838513/gcdasyncudpsocket-cannot-bind-port-on-ios-simulator(设置SO_REUSE套接字选项)。 –
谢谢,我也认为它会把它整理出来,但事实并非如此。 – Funkycochise
你解决了这个问题吗? – RMRAHUL