您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 廣播開發實作:用 AsyncUdpSocket 發送 UDP 廣播並接收回應

編輯:iOS 相關資訊

在區域網路中尋找服務(例如掃描同一網段內的裝置)時,UDP 廣播是最直接的做法。以下示範以 AsyncUdpSocket 發送廣播封包,並在服務端回應後開始正式通訊。

- (void)init {
    AsyncUdpSocket *socket = [[AsyncUdpSocket alloc] initWithDelegate:self];
    [socket bindToPort:16747];

    NSTimeInterval timeout = 5000;
    NSString *request = @"quick_stat";
    NSData *data = [NSData dataWithData:[request dataUsingEncoding:NSASCIIStringEncoding]];

    UInt16 port = 8081;
    NSError *error;

    // 關鍵一步:開放廣播能力
    [socket enableBroadcast:YES error:&error];

    // 送往 255.255.255.255,等同「整個網段都收」
    [socket sendData:data toHost:@"255.255.255.255" port:port withTimeout:timeout tag:1];

    [socket receiveWithTimeout:-1 tag:0];
    NSLog(@"begin scan");
}

四個回呼的分工

AsyncUdpSocket 把收發結果拆成對稱的成對回呼,成功與失敗各自成對,除錯時很容易定位問題出在哪一層。

// 成功收到資料
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock
     didReceiveData:(NSData *)data
            withTag:(long)tag
           fromHost:(NSString *)host
               port:(UInt16)port {
    NSString *result = [[NSString alloc] initWithData:data
                                             encoding:NSASCIIStringEncoding];
    NSLog(@"%@", result);
    NSLog(@"received");
    return YES;
}

// 收不到(逾時或 socket 出問題)
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock
didNotReceiveDataWithTag:(long)tag
           dueToError:(NSError *)error {
    NSLog(@"not received");
    return YES;
}

// 發送失敗
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock
didNotSendDataWithTag:(long)tag
           dueToError:(NSError *)error {
    NSLog(@"%@", error);
    NSLog(@"not send");
    return YES;
}

// 發送成功
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock
   didSendDataWithTag:(long)tag {
    NSLog(@"send");
    return YES;
}

// 連線關閉
- (BOOL)onUdpSocketDidClose:(AsyncUdpSocket *)sock {
    NSLog(@"closed");
    return YES;
}

幾個實務上的注意事項

  • enableBroadcast 必須在送資料之前呼叫,否則多數網路介面會直接丟棄目的地位址為 255.255.255.255 的封包。
  • bindToPort 決定了你能收到什麼。廣播回應通常回到發送來源埠,若收不到回應,先確認本地綁定的埠號是否與對方回傳時使用的埠一致。
  • timeout 單位是秒。範例中的 5000 秒顯然是筆誤,實務上多半設 3 到 10 秒即可;receiveWithTimeout:-1 則代表無限期等待。
  • 接收要持續重新下單。AsyncUdpSocket 一次 receive 只對應一個封包,收到後若要繼續收,必須在回呼中再次呼叫 receive 方法,這與一般 socket 的迴圈模型不同。
  • 跨網段不會成功。UDP 廣播預設不穿過路由器,因此這套方案只適用於同一個廣播網域內的裝置發現。若需要跨網段,得改用組播(multicast)或交由後端做註冊式服務發現。
  • 非同步 API 的替代。AsyncSocket/AsyncUdpSocket 已停止維護,新專案可改用 GCDAsyncSocket,或直接以 Network.framework 的 NWConnection 搭配 .udp 參數實作。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved