今天就跟大家聊聊有關(guān)怎么在iOS中實(shí)現(xiàn)WebSocket長鏈接,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
成都創(chuàng)新互聯(lián)公司是一家集網(wǎng)站建設(shè),長嶺企業(yè)網(wǎng)站建設(shè),長嶺品牌網(wǎng)站建設(shè),網(wǎng)站定制,長嶺網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,長嶺網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。
WebSocket
WebSocket 是 HTML5 一種新的協(xié)議。它實(shí)現(xiàn)了瀏覽器與服務(wù)器全雙工通信,能更好的節(jié)省服務(wù)器資源和帶寬并達(dá)到實(shí)時(shí)通訊,它建立在 TCP 之上,同 HTTP 一樣通過 TCP 來傳輸數(shù)據(jù),但是它和 HTTP 最大不同是:WebSocket 是一種雙向通信協(xié)議.
由于項(xiàng)目需要?jiǎng)?chuàng)建一個(gè)聊天室,需要通過長鏈接,和后臺保持通訊,進(jìn)行聊天,并且實(shí)時(shí)進(jìn)行熱點(diǎn)消息的推送.
目前Facebook的SocketRocket應(yīng)該是目前最好的關(guān)于SocketRocket使用的框架了.而且簡單易用.
使用
一般一個(gè)項(xiàng)目在啟動(dòng)后的某個(gè)時(shí)機(jī)會啟動(dòng)創(chuàng)建一個(gè)長鏈接,如果需要多個(gè)就多次創(chuàng)建.如果只要一個(gè)就可以封裝為一個(gè)單例,全局使用.
可以使用podpod管理庫, 在podfile中加入
pod 'SocketRocket'
在使用命令行工具cd到當(dāng)前工程 安裝
pod install
導(dǎo)入頭文件后即可使用.
為求穩(wěn)定,我的做法是copy的FaceBook里SocketRocket庫到項(xiàng)目里. --> SocketRocket地址
1.首先創(chuàng)建一個(gè)名為 WebSocketManager 的單例類,
+(instancetype)shared;
2.創(chuàng)建一個(gè)枚舉,分別表示W(wǎng)ebSocket的鏈接狀態(tài)
typedef NS_ENUM(NSUInteger,WebSocketConnectType){ WebSocketDefault = 0, //初始狀態(tài),未連接,不需要重新連接 WebSocketConnect, //已連接 WebSocketDisconnect //連接后斷開,需要重新連接 };
3.創(chuàng)建連接
//建立長連接 - (void)connectServer;
4.處理連接成功的結(jié)果;
-(void)webSocketDidOpen:(RMWebSocket *)webSocket; //連接成功回調(diào)
5.處理連接失敗的結(jié)果
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;//連接失敗回調(diào)
6.接收消息
///接收消息回調(diào),需要提前和后臺約定好消息格式. - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(nonnull NSString *)string
7.關(guān)閉連接
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;///關(guān)閉連接回調(diào)的代理
8.為保持長鏈接的連接狀態(tài),需要定時(shí)向后臺發(fā)送消息,就是俗稱的:心跳包.
需要?jiǎng)?chuàng)建一個(gè)定時(shí)器,固定時(shí)間發(fā)送消息.
9.鏈接斷開情況處理:
首先判斷是否是主動(dòng)斷開,如果是主動(dòng)斷開就不作處理.
如果不是主動(dòng)斷開鏈接,需要做重新連接的邏輯.
具體代碼如下:
WebSocketManager.h 中的代碼
#import#import "RMWebSocket.h" typedef NS_ENUM(NSUInteger,WebSocketConnectType){ WebSocketDefault = 0, //初始狀態(tài),未連接 WebSocketConnect, //已連接 WebSocketDisconnect //連接后斷開 }; @class WebSocketManager; @protocol WebSocketManagerDelegate - (void)webSocketManagerDidReceiveMessageWithString:(NSString *)string; @end NS_ASSUME_NONNULL_BEGIN @interface WebSocketManager : NSObject @property (nonatomic, strong) RMWebSocket *webSocket; @property(nonatomic,weak) id delegate; @property (nonatomic, assign) BOOL isConnect; //是否連接 @property (nonatomic, assign) WebSocketConnectType connectType; +(instancetype)shared; - (void)connectServer;//建立長連接 - (void)reConnectServer;//重新連接 - (void)RMWebSocketClose;//關(guān)閉長連接 - (void)sendDataToServer:(NSString *)data;//發(fā)送數(shù)據(jù)給服務(wù)器 @end NS_ASSUME_NONNULL_END
WebSocketManager.m 中的代碼
#import "WebSocketManager.h" @interface WebSocketManager ()@property (nonatomic, strong) NSTimer *heartBeatTimer; //心跳定時(shí)器 @property (nonatomic, strong) NSTimer *netWorkTestingTimer; //沒有網(wǎng)絡(luò)的時(shí)候檢測網(wǎng)絡(luò)定時(shí)器 @property (nonatomic, assign) NSTimeInterval reConnectTime; //重連時(shí)間 @property (nonatomic, strong) NSMutableArray *sendDataArray; //存儲要發(fā)送給服務(wù)端的數(shù)據(jù) @property (nonatomic, assign) BOOL isActivelyClose; //用于判斷是否主動(dòng)關(guān)閉長連接,如果是主動(dòng)斷開連接,連接失敗的代理中,就不用執(zhí)行 重新連接方法 @end @implementation WebSocketManager +(instancetype)shared{ static WebSocketManager *_instance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[self alloc]init]; }); return _instance; } - (instancetype)init { self = [super init]; if(self){ self.reConnectTime = 0; self.isActivelyClose = NO; self.sendDataArray = [[NSMutableArray alloc] init]; } return self; } //建立長連接 - (void)connectServer{ self.isActivelyClose = NO; self.webSocket.delegate = nil; [self.webSocket close]; _webSocket = nil; // self.webSocket = [[RMWebSocket alloc] initWithURL:[NSURL URLWithString:@"https://dev-im-gateway.runxsports.com/ws/token=88888888"]]; self.webSocket = [[RMWebSocket alloc] initWithURL:[NSURL URLWithString:@"ws://chat.workerman.net:7272"]]; self.webSocket.delegate = self; [self.webSocket open]; } - (void)sendPing:(id)sender{ [self.webSocket sendPing:nil error:NULL]; } #pragma mark -------------------------------------------------- #pragma mark - socket delegate ///開始連接 -(void)webSocketDidOpen:(RMWebSocket *)webSocket{ NSLog(@"socket 開始連接"); self.isConnect = YES; self.connectType = WebSocketConnect; [self initHeartBeat];///開始心跳 } ///連接失敗 -(void)webSocket:(RMWebSocket *)webSocket didFailWithError:(NSError *)error{ NSLog(@"連接失敗"); self.isConnect = NO; self.connectType = WebSocketDisconnect; DLog(@"連接失敗,這里可以實(shí)現(xiàn)掉線自動(dòng)重連,要注意以下幾點(diǎn)"); DLog(@"1.判斷當(dāng)前網(wǎng)絡(luò)環(huán)境,如果斷網(wǎng)了就不要連了,等待網(wǎng)絡(luò)到來,在發(fā)起重連"); DLog(@"3.連接次數(shù)限制,如果連接失敗了,重試10次左右就可以了"); //判斷網(wǎng)絡(luò)環(huán)境 if (AFNetworkReachabilityManager.sharedManager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable){ //沒有網(wǎng)絡(luò) [self noNetWorkStartTestingTimer];//開啟網(wǎng)絡(luò)檢測定時(shí)器 }else{ //有網(wǎng)絡(luò) [self reConnectServer];//連接失敗就重連 } } ///接收消息 -(void)webSocket:(RMWebSocket *)webSocket didReceiveMessageWithString:(NSString *)string{ NSLog(@"接收消息---- %@",string); if ([self.delegate respondsToSelector:@selector(webSocketManagerDidReceiveMessageWithString:)]) { [self.delegate webSocketManagerDidReceiveMessageWithString:string]; } } ///關(guān)閉連接 -(void)webSocket:(RMWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean{ self.isConnect = NO; if(self.isActivelyClose){ self.connectType = WebSocketDefault; return; }else{ self.connectType = WebSocketDisconnect; } DLog(@"被關(guān)閉連接,code:%ld,reason:%@,wasClean:%d",code,reason,wasClean); [self destoryHeartBeat]; //斷開連接時(shí)銷毀心跳 //判斷網(wǎng)絡(luò)環(huán)境 if (AFNetworkReachabilityManager.sharedManager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable){ //沒有網(wǎng)絡(luò) [self noNetWorkStartTestingTimer];//開啟網(wǎng)絡(luò)檢測 }else{ //有網(wǎng)絡(luò) NSLog(@"關(guān)閉連接"); _webSocket = nil; [self reConnectServer];//連接失敗就重連 } } ///ping -(void)webSocket:(RMWebSocket *)webSocket didReceivePong:(NSData *)pongData{ NSLog(@"接受pong數(shù)據(jù)--> %@",pongData); } #pragma mark - NSTimer //初始化心跳 - (void)initHeartBeat{ //心跳沒有被關(guān)閉 if(self.heartBeatTimer) { return; } [self destoryHeartBeat]; dispatch_main_async_safe(^{ self.heartBeatTimer = [NSTimer timerWithTimeInterval:10 target:self selector:@selector(senderheartBeat) userInfo:nil repeats:true]; [[NSRunLoop currentRunLoop]addTimer:self.heartBeatTimer forMode:NSRunLoopCommonModes]; }) } //重新連接 - (void)reConnectServer{ if(self.webSocket.readyState == RM_OPEN){ return; } if(self.reConnectTime > 1024){ //重連10次 2^10 = 1024 self.reConnectTime = 0; return; } WS(weakSelf); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.reConnectTime *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ if(weakSelf.webSocket.readyState == RM_OPEN && weakSelf.webSocket.readyState == RM_CONNECTING) { return; } [weakSelf connectServer]; // CTHLog(@"正在重連......"); if(weakSelf.reConnectTime == 0){ //重連時(shí)間2的指數(shù)級增長 weakSelf.reConnectTime = 2; }else{ weakSelf.reConnectTime *= 2; } }); } //發(fā)送心跳 - (void)senderheartBeat{ //和服務(wù)端約定好發(fā)送什么作為心跳標(biāo)識,盡可能的減小心跳包大小 WS(weakSelf); dispatch_main_async_safe(^{ if(weakSelf.webSocket.readyState == RM_OPEN){ [weakSelf sendPing:nil]; } }); } //沒有網(wǎng)絡(luò)的時(shí)候開始定時(shí) -- 用于網(wǎng)絡(luò)檢測 - (void)noNetWorkStartTestingTimer{ WS(weakSelf); dispatch_main_async_safe(^{ weakSelf.netWorkTestingTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:weakSelf selector:@selector(noNetWorkStartTesting) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:weakSelf.netWorkTestingTimer forMode:NSDefaultRunLoopMode]; }); } //定時(shí)檢測網(wǎng)絡(luò) - (void)noNetWorkStartTesting{ //有網(wǎng)絡(luò) if(AFNetworkReachabilityManager.sharedManager.networkReachabilityStatus != AFNetworkReachabilityStatusNotReachable) { //關(guān)閉網(wǎng)絡(luò)檢測定時(shí)器 [self destoryNetWorkStartTesting]; //開始重連 [self reConnectServer]; } } //取消網(wǎng)絡(luò)檢測 - (void)destoryNetWorkStartTesting{ WS(weakSelf); dispatch_main_async_safe(^{ if(weakSelf.netWorkTestingTimer) { [weakSelf.netWorkTestingTimer invalidate]; weakSelf.netWorkTestingTimer = nil; } }); } //取消心跳 - (void)destoryHeartBeat{ WS(weakSelf); dispatch_main_async_safe(^{ if(weakSelf.heartBeatTimer) { [weakSelf.heartBeatTimer invalidate]; weakSelf.heartBeatTimer = nil; } }); } //關(guān)閉長連接 - (void)RMWebSocketClose{ self.isActivelyClose = YES; self.isConnect = NO; self.connectType = WebSocketDefault; if(self.webSocket) { [self.webSocket close]; _webSocket = nil; } //關(guān)閉心跳定時(shí)器 [self destoryHeartBeat]; //關(guān)閉網(wǎng)絡(luò)檢測定時(shí)器 [self destoryNetWorkStartTesting]; } //發(fā)送數(shù)據(jù)給服務(wù)器 - (void)sendDataToServer:(NSString *)data{ [self.sendDataArray addObject:data]; //[_webSocket sendString:data error:NULL]; //沒有網(wǎng)絡(luò) if (AFNetworkReachabilityManager.sharedManager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) { //開啟網(wǎng)絡(luò)檢測定時(shí)器 [self noNetWorkStartTestingTimer]; } else //有網(wǎng)絡(luò) { if(self.webSocket != nil) { // 只有長連接OPEN開啟狀態(tài)才能調(diào) send 方法,不然會Crash if(self.webSocket.readyState == RM_OPEN) { // if (self.sendDataArray.count > 0) // { // NSString *data = self.sendDataArray[0]; [_webSocket sendString:data error:NULL]; //發(fā)送數(shù)據(jù) // [self.sendDataArray removeObjectAtIndex:0]; // // } } else if (self.webSocket.readyState == RM_CONNECTING) //正在連接 { DLog(@"正在連接中,重連后會去自動(dòng)同步數(shù)據(jù)"); } else if (self.webSocket.readyState == RM_CLOSING || self.webSocket.readyState == RM_CLOSED) //斷開連接 { //調(diào)用 reConnectServer 方法重連,連接成功后 繼續(xù)發(fā)送數(shù)據(jù) [self reConnectServer]; } } else { [self connectServer]; //連接服務(wù)器 } } } @end
注意點(diǎn)
我們在發(fā)送消息之前,也就是調(diào)用 senderheartBeat/ sendDataToServer:方法之前,一定要判斷當(dāng)前scoket是否連接,如果不是連接狀態(tài),程序則會crash。
iOS手機(jī)屏幕息屏或者回主頁的時(shí)候有可能會造成鏈接斷開,我這邊的處理是在回到屏幕的時(shí)候,判斷狀態(tài),如果已經(jīng)斷開,就重新連接.
在 AppDelegate 中:
- (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. if ([WebSocketManager shared].connectType == WebSocketDisconnect) { [[WebSocketManager shared] connectServer]; } }
看完上述內(nèi)容,你們對怎么在iOS中實(shí)現(xiàn)WebSocket長鏈接有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。