同樣出自 CocoaAsyncSocket 專案,AsyncUdpSocket 是 TCP 版本的姊妹套件,專門處理 UDP 的非同步收發。官方網站:https://code.google.com/p/cocoaasyncsocket/
把 AsyncUdpSocket.h 與 AsyncUdpSocket.m 加入專案,然後在自訂的工具類別中寫入以下程式碼。
#pragma mark udp
-(void)sendSearchBroadcast {
NSString *bchost = @"255.255.255.255"; // 有限廣播位址
[self sendToUDPServer:@"hello udp" address:bchost port:BCPORT];
}
-(void)sendToUDPServer:(NSString *)msg address:(NSString *)address port:(int)port {
AsyncUdpSocket *udpSocket =
[[[AsyncUdpSocket alloc] initWithDelegate:self] autorelease];
NSLog(@"address:%@, port:%d, msg:%@", address, port, msg);
[udpSocket receiveWithTimeout:10 tag:2]; // 必須先設定接收,否則收不到任何資料
[udpSocket enableBroadcast:YES error:nil]; // 要發廣播必須先開啟
NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];
[udpSocket sendData:data toHost:address port:port withTimeout:10 tag:1];
}
-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock
didReceiveData:(NSData *)data
withTag:(long)tag
fromHost:(NSString *)host
port:(UInt16)port {
NSString *rData = [[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding] autorelease];
NSLog(@"onUdpSocket:didReceiveData:---%@", rData);
return YES;
}
-(void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag {
NSLog(@"didSendDataWithTag----");
}
-(void)onUdpSocket:(AsyncUdpSocket *)sock
didNotSendDataWithTag:(long)tag
dueToError:(NSError *)error {
NSLog(@"didNotSendDataWithTag----");
}
-(void)onUdpSocket:(AsyncUdpSocket *)sock
didNotReceiveDataWithTag:(long)tag
dueToError:(NSError *)error {
NSLog(@"didNotReceiveDataWithTag----");
}
-(void)onUdpSocketDidClose:(AsyncUdpSocket *)sock {
NSLog(@"onUdpSocketDidClose----");
}
不呼叫 receiveWithTimeout: 就收不到任何資料。UDP 是無連線協定,AsyncUdpSocket 不會自動幫你準備接收;必須先設定接收逾時,否則 didReceiveData 永遠不會被觸發。這與 TCP 版本的行为不同,是移植程式碼時最常出錯的地方。
發送廣播前必須 enableBroadcast。預設情況下 socket 不允許廣播,未開啟就送出 255.255.255.255 會直接失敗。
UDP 不保證送達、不保證順序、也不保證不被重複接收。上面的範例只用於局域網內的裝置發現(例如搜尋印表機、區域連線),這類場景丟失一两个封包影響有限。若應用於商務資料傳輸,務必在應用層自行實作序號、 Acknowledgement 與重送機制,或改用 TCP。
此外,iOS 對長時間運行的背景網路連線有嚴格限制,UDP socket 在 App 進入背景後通常會被系統關閉,需要搭配 VoIP push 或 background fetch 等特殊能力才能維持。