我正在使用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