在 iOS 上做低階的 TCP 通訊,AsyncSocket 是一個相當好用的第三方類別,它把 socket 的 non-blocking 細節與 delegate 回呼包裝得很乾淨。以下用一個範例展示同一個 App 如何同時扮演伺服器與客戶端。
使用前請先導入 AsyncSocket 類別檔,並在專案中連結 CFNetwork 系統框架。
#import <UIKit/UIKit.h>
#import "AsyncSocket.h"
@interface ViewController : UIViewController {
NSMutableArray *_socketArray; // 存放已接受的連線
AsyncSocket *_sendSocket; // 作為客戶端:發送
AsyncSocket *_recvSocket; // 作為伺服器:接收
}
@property (retain, nonatomic) IBOutlet UITextField *ipField;
@property (retain, nonatomic) IBOutlet UITextField *sendField;
@property (retain, nonatomic) IBOutlet UITextView *msgView;
- (IBAction)conClick:(id)sender;
- (IBAction)sendClick:(id)sender;
@end
#import "ViewController.h"
@implementation ViewController
@synthesize ipField;
@synthesize sendField;
@synthesize msgView;
- (void)viewDidLoad {
[super viewDidLoad];
_socketArray = [[NSMutableArray alloc] init];
_sendSocket = [[AsyncSocket alloc] initWithDelegate:self];
_recvSocket = [[AsyncSocket alloc] initWithDelegate:self];
// 伺服器端開始監聽 5566
[_recvSocket acceptOnPort:5566 error:nil];
}
// 伺服器端接受到了新的連線
- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket {
[_socketArray addObject:newSocket];
[newSocket readDataWithTimeout:-1 tag:0]; // -1 代表不設逾時
}
// 收到資料
- (void)onSocket:(AsyncSocket *)sock
didReadData:(NSData *)data
withTag:(long)tag {
NSString *string = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
self.msgView.text = [NSString stringWithFormat:@"%@%@:%@\n",
self.msgView.text, sock.connectedHost, string];
[sock readDataWithTimeout:-1 tag:0]; // 繼續循環接收
}
// 連線到伺服器
- (IBAction)conClick:(id)sender {
if (_sendSocket.isConnected) {
[_sendSocket disconnect];
}
[_sendSocket connectToHost:self.ipField.text
onPort:5566
withTimeout:30
error:nil];
}
// 發送訊息
- (IBAction)sendClick:(id)sender {
NSData *data = [self.sendField.text dataUsingEncoding:NSUTF8StringEncoding];
[_sendSocket writeData:data withTimeout:30 tag:0];
self.sendField.text = @"";
}
- (void)onSocket:(AsyncSocket *)sock
didConnectToHost:(NSString *)host
port:(UInt16)port {
NSLog(@"連接伺服器成功");
}
- (void)onSocketDidDisconnect:(AsyncSocket *)sock {
NSLog(@"斷開連接");
}
- (void)dealloc {
[ipField release];
[sendField release];
[msgView release];
[super dealloc];
}
- (void)viewDidUnload {
[self setIpField:nil];
[super viewDidUnload];
}
@end
AsyncSocket 的核心是「先登記、再等待回呼」。你呼叫 readDataWithTimeout:tag: 之後並不會阻塞,而是等資料到齊時由 onSocket:didReadData:withTag: 通知你。因此想要持續接收,就必須在回呼方法裡再一次登記讀取——這就是範例中「循環」的由來,也是許多人初學時卡住的地方。
tag 參數的用途是標記這次讀取的意圖。當你的協定有多種訊息類型時,可以用不同的 tag 區分,在回呼中判斷該如何處理。
NWConnection(Network.framework)。