TCP 適合要求可靠傳輸的情境,但當需求是「把同一份畫面即時推送給多台裝置」時,UDP 的低延遲與無連線特性更合適。本文以一個教學廣播 demo 為例:教師端定時截屏並群發,學生端接收後顯示。
用一個巨集 STU 切換角色,同一份程式碼可編譯成教師端或學生端:
#import "ViewController.h"
#import "AsyncUdpSocket.h"
#import "ZCScreenShot.h"
#define STU 1
@interface ViewController ()
{
AsyncUdpSocket *sendSocket; // 負責發送
AsyncUdpSocket *serverSocket; // 負責接收
UILabel *numberLabel; // 教師端顯示用
UIImageView *imageView; // 學生端顯示用
}
@property (nonatomic, strong) NSMutableArray *ipArray;
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.ipArray = [NSMutableArray array];
[self createView];
[self createSocket];
if (STU) {
// 學生端啟動即報到
[sendSocket sendData:[@"簽到!" dataUsingEncoding:NSUTF8StringEncoding]
toHost:@"10.8.155.36"
port:5678
withTimeout:-1
tag:100];
} else {
// 教師端啟動定時截屏廣播
[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(timerClick)
userInfo:nil
repeats:YES];
}
}
- (void)createSocket {
sendSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
serverSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
// 綁定 port 後才會收到送往該 port 的封包
[serverSocket bindToPort:5678 error:nil];
// timeout 傳 -1 表示不設上限,持續等待
[serverSocket receiveWithTimeout:-1 tag:100];
}
- (void)timerClick {
if (self.ipArray.count == 0) return;
float r = arc4random() % 256 / 255.0;
float g = arc4random() % 256 / 255.0;
float b = arc4random() % 256 / 255.0;
numberLabel.backgroundColor = [UIColor colorWithRed:r green:g blue:b alpha:1];
numberLabel.text = @"抽煙不?跟我一塊兒吧";
numberLabel.font = [UIFont boldSystemFontOfSize:40];
// 第一個參數為範圍,第二個為要渲染的 view
UIImage *image = [ZCScreenShot beginImageContext:self.view.frame View:self.view];
for (NSString *ip in self.ipArray) {
[sendSocket sendData:UIImageJPEGRepresentation(image, 0.1)
toHost:ip
port:5678
withTimeout:-1
tag:100];
}
}
- (void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag {
NSLog(@"發送完成");
}
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock
didReceiveData:(NSData *)data
withTag:(long)tag
fromHost:(NSString *)host
port:(UInt16)port {
if (STU) {
imageView.image = [UIImage imageWithData:data];
} else {
// 教師端:記錄新的學生 IP,重複者忽略
if (![self.ipArray containsObject:host]) {
[self.ipArray addObject:host];
}
}
[sock receiveWithTimeout:-1 tag:100]; // 繼續監聽下一個封包
return YES;
}
必須持續重新呼叫 receive。AsyncUdpSocket 是「一次性」的接收設計:每次成功收到封包後,若不再呼叫 receiveWithTimeout:tag:,後續封包就不會再觸發回呼。這是新手最常踩的坑。
UDP 不可靠。封包可能遺失、重複或亂序抵達,也不保證大小。若傳輸內容重要,需在應用層自行加入序號、校驗與重送機制。以本例的截屏廣播而言,掉幾幀無傷大雅,因此直接用 UDP 是合理的取捨。
單一封包有大小上限。實務上承載於 IPv4 的 UDP datagram 建議控制在 64KB 以內,且要避開以太網 MTU 引發的分片。範例把 JPEG 品質壓到 0.1 就是為了縮小体积。
截屏的先天限制。renderInContext: 只能渲染 UIView 的 layer 樹,無法擷取 video 播放畫面。若要截取 AVPlayer 或 OpenGL ES 的內容,需改用 CVOpenGLESTextureCache 或直接讀取 GL 緩衝區。
硬編碼的 IP 需替換。範例中的 10.8.155.36 只是當時的內網位址。實務上可透過 Bonjour / NSNetService 做區域網路服務發現,或讓教師端本身開一個 UDP 埠接收廣播報到,避免手動設定。
AsyncUdpSocket 已多年未更新。新專案建議改用BSD Socket 搭配 GCD,或使用蘋果原生的 Network.framework(NWConnection)在 iOS 12 以上完成同樣的事,程式碼更簡潔且支援 IPv6 與加密傳輸。