要做類似 QQ 那樣的即時聊天,就需要客戶端與服務端建立長連接,在這條通道上雙向收發消息;客戶端通常還要定時發送心跳包來維持連接、檢測斷線。iOS 上實現這件事,最經典的第三方庫是 AsyncSocket。本文從它的特性講到封裝一個可複用的單例通訊層。
下載地址:CocoaAsyncSocket。這個庫主要包含兩個類:
它的核心特性:
實戰中通常會在它之上再封一層,對外只暴露幾個語義清晰的接口:連接、斷開、發送消息;收到的消息則通過通知、代理或 block 拋出去。由於一個用戶一般只需要一條長連接,用單例來承載最合適。
// LGSocketServe.h #import <Foundation/Foundation.h> #import "AsyncSocket.h" @interface LGSocketServe : NSObject <AsyncSocketDelegate> + (LGSocketServe *)sharedSocketServe; @end
// LGSocketServe.m
#import "LGSocketServe.h"
@implementation LGSocketServe
static LGSocketServe *socketServe = nil;
#pragma mark - 單例
+ (LGSocketServe *)sharedSocketServe
{
@synchronized(self) {
if (socketServe == nil) {
socketServe = [[[self class] alloc] init];
}
}
return socketServe;
}
// 重寫 allocWithZone:,杜絕外部創建第二個實例
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (socketServe == nil) {
socketServe = [super allocWithZone:zone];
return socketServe;
}
}
return nil;
}
@end
// LGSocketServe.h @property (nonatomic, strong) AsyncSocket *socket; // socket 實例 - (void)startConnectSocket;
// LGSocketServe.m
// 服務端地址與端口,按實際情況替換
#define HOST @"192.168.0.1"
#define PORT 8080
// 連接超時(秒)
#define TIME_OUT 20
- (void)startConnectSocket
{
self.socket = [[AsyncSocket alloc] initWithDelegate:self];
[self.socket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
if (![self SocketOpen:HOST port:PORT]) {
// 連接失敗的處理
}
}
- (NSInteger)SocketOpen:(NSString *)addr port:(NSInteger)port
{
if (![self.socket isConnected]) {
NSError *error = nil;
[self.socket connectToHost:addr onPort:port withTimeout:TIME_OUT error:&error];
}
return 0;
}
別忘了設置 AsyncSocketDelegate 代理。連接成功後會異步回調:
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
// 異步返回的連接成功通知
NSLog(@"didConnectToHost");
}
長連接最大的敵人是 NAT 超時與網絡我爸——中間設備會悄悄丟棄長時間沒有數據的連接。解法就是定時發一個小包。
// LGSocketServe.h @property (nonatomic, retain) NSTimer *heartTimer; // 心跳計時器
// LGSocketServe.m
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(@"didConnectToHost");
// 通過定時器週期性發送消息,檢測長連接是否還活着
self.heartTimer = [NSTimer scheduledTimerWithTimeInterval:2
target:self
selector:@selector(checkLongConnectByServe)
userInfo:nil
repeats:YES];
[self.heartTimer fire];
}
// 心跳
- (void)checkLongConnectByServe
{
// 向服務端發送約定的固定內容
NSString *longConnect = @"connect is here";
NSData *data = [longConnect dataUsingEncoding:NSUTF8StringEncoding];
[self.socket writeData:data withTimeout:1 tag:1];
}
心跳內容需與服務端約定一致,間隔也要雙方對齊——發得太頻繁浪費流量與電量,太稀疏則起不到探活作用。
// LGSocketServe.h - (void)cutOffSocket;
// LGSocketServe.m
- (void)cutOffSocket
{
self.socket.userData = SocketOfflineByUser;
[self.socket disconnect];
}
標記為「用戶主動斷開」的意義在於:後續的斷線回調中要據此決定不重連,否則用戶註銷後還會被自動拉回來。
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
NSLog(@"willDisconnectWithError %ld err = %@",
(long)sock.userData, [err description]);
// 57 表示網絡不可達
if (err.code == 57) {
self.socket.userData = SocketOfflineByWifiCut;
}
}
- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
NSLog(@"sorry the connect is failure %ld", (long)sock.userData);
if (sock.userData == SocketOfflineByServer) {
// 服務端掉線或網絡異常,執行重連
[self startConnectSocket];
}
else if (sock.userData == SocketOfflineByUser) {
// 用戶主動斷開,不重連
return;
}
else if (sock.userData == SocketOfflineByWifiCut) {
// 網絡本身不通,等網絡恢復再說
return;
}
}
這裡的設計要點是:用 userData 記錄「為什麼斷開」,再在統一的重連入口中據此分流。生產環境中還應加上重連次數上限與退避(backoff)策略,避免服務端宕機時所有客戶端瘋狂重試。
// LGSocketServe.h - (void)sendMessage:(id)message;
// LGSocketServe.m
// 寫入超時,-1 表示不使用超時
#define WRITE_TIME_OUT -1
- (void)sendMessage:(id)message
{
NSData *cmdData = [message dataUsingEncoding:NSUTF8StringEncoding];
[self.socket writeData:cmdData withTimeout:WRITE_TIME_OUT tag:1];
}
// 發送成功後的回調
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
// 通常在此處觸發一次讀取
}
// LGSocketServe.m
// 讀取超時,-1 表示不使用超時
#define READ_TIME_OUT -1
#define MAX_BUFFER 1024
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
// 寫完就準備讀
[self.socket readDataWithTimeout:-1 buffer:nil bufferOffset:0 maxLength:MAX_BUFFER tag:0];
}
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
// 服務端返回的數據量較大時可能分多次到達,
// 因此限定每次最多讀 MAX_BUFFER;
// 當 data.length < MAX_BUFFER 時,可認為一個完整消息已收齊,再進行解析
if (data.length < MAX_BUFFER) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableLeaves
error:nil];
NSLog(@"%@", dic);
// 解析後的結果可通過通知、代理、block 拋給業務層
}
// 繼續讀下一段
[self.socket readDataWithTimeout:READ_TIME_OUT buffer:nil bufferOffset:0 maxLength:MAX_BUFFER tag:0];
}
這裡有個實務上的重要提醒:用 data.length < MAX_BUFFER 來判斷「消息收完」是一個樸素但不可靠的做法。TCP 是字節流,沒有天然的「消息邊界」,一旦某條消息長度恰好等於 buffer 大小,或者網絡分片恰好對齊,判斷就會出錯。嚴謹的做法是在協議層約定「消息頭 + 消息體長度」的粘包/拆包格式,先讀定長的頭部解析出長度,再按長度讀齊 body。
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
// 取出尚未讀取的緩衝區,避免丟數據
NSData *unreadData = [sock unreadData];
if (unreadData.length > 0) {
[self onSocket:sock didReadData:unreadData withTag:0];
} else {
NSLog(@"willDisconnectWithError %ld err = %@",
(long)sock.userData, [err description]);
if (err.code == 57) {
self.socket.userData = SocketOfflineByWifiCut;
}
}
}
通過 unreadData 把斷線瞬間還沒處理完的數據撈出來交給解析邏輯,能顯著減少「最後一條消息丟失」的問題。
#import "LGSocketServe.h" LGSocketServe *socketServe = [LGSocketServe sharedSocketServe]; // 連接前先主動斷開,避免上次的連接沒關乾淨導致崩潰 [socketServe cutOffSocket]; socketServe.socket.userData = SocketOfflineByServer; [socketServe startConnectSocket]; // 發送消息("hello world" 僅為示例,實際格式需與服務端約定) [socketServe sendMessage:@"hello world"];
AsyncSocket 已多年不再維護,新項目建議改用蘋果官方的 NWConnection(Network.framework) 或 WebSocket 相關方案。若後端支持 WebSocket,直接用 NSURLSessionWebSocketTask(iOS 13+)會省下大量協議封裝工作;若必須走裸 TCP,NWConnection 提供了更清晰的狀態機與更完善的 IPv6 / 網絡路徑切換支持。
無論用哪個庫,長連接的三件核心事務是不變的:心跳探活、斷線分類重連、粘包拆包。把這三件事做紮實,即時通訊的基本盤就穩了。