iOS使用GCDSocketManager实现长连接的方法
.h文件
#import#import"GCDAsyncSocket.h" @interfaceGCDSocketManager:NSObject @property(nonatomic,strong)GCDAsyncSocket*socket; //单例 +(instancetype)sharedSocketManager; //连接 -(void)connectToServer; //断开 -(void)cutOffSocket; @end
.m文件
#import"GCDSocketManager.h" #defineSocketHost@"地址" #defineSocketPort端口 @interfaceGCDSocketManager()//握手次数 @property(nonatomic,assign)NSIntegerpushCount; //断开重连定时器 @property(nonatomic,strong)NSTimer*timer; //重连次数 @property(nonatomic,assign)NSIntegerreconnectCount; @end @implementationGCDSocketManager //全局访问点 +(instancetype)sharedSocketManager{ staticGCDSocketManager*_instance=nil; staticdispatch_once_tonceToken; dispatch_once(&onceToken,^{ _instance=[[selfalloc]init]; }); return_instance; } //可以在这里做一些初始化操作 -(instancetype)init { self=[superinit]; if(self){ } returnself; } #pragmamark请求连接 //连接 -(void)connectToServer{ self.pushCount=0; self.socket=[[GCDAsyncSocketalloc]initWithDelegate:selfdelegateQueue:dispatch_get_main_queue()]; NSError*error=nil; [self.socketconnectToHost:SocketHostonPort:SocketPorterror:&error]; if(error){ DLog(@"SocketConnectError:%@",error); } } #pragmamark连接成功 //连接成功的回调 -(void)socket:(GCDAsyncSocket*)sockdidConnectToHost:(NSString*)hostport:(uint16_t)port{ DLog(@"socket连接成功"); [selfsendDataToServer]; } //连接成功后向服务器发送数据 -(void)sendDataToServer{ //发送数据代码省略... //发送 [self.socketwriteData:jsonDatawithTimeout:-1tag:1]; //读取数据 [self.socketreadDataWithTimeout:-1tag:200]; } //连接成功向服务器发送数据后,服务器会有响应 -(void)socket:(GCDAsyncSocket*)sockdidReadData:(NSData*)datawithTag:(long)tag{ [self.socketreadDataWithTimeout:-1tag:200]; //服务器推送次数 self.pushCount++; //在这里进行校验操作,情况分为成功和失败两种,成功的操作一般都是拉取数据 } #pragmamark连接失败 //连接失败的回调 -(void)socketDidDisconnect:(GCDAsyncSocket*)sockwithError:(NSError*)err{ DLog(@"Socket连接失败"); self.pushCount=0; NSUserDefaults*userDefaults=[NSUserDefaultsstandardUserDefaults]; NSString*currentStatu=[userDefaultsvalueForKey:@"Statu"]; //程序在前台才进行重连 if([currentStatuisEqualToString:@"foreground"]){ //重连次数 self.reconnectCount++; //如果连接失败累加1秒重新连接减少服务器压力 NSTimer*timer=[NSTimerscheduledTimerWithTimeInterval:1.0*self.reconnectCounttarget:selfselector:@selector(reconnectServer)userInfo:nilrepeats:NO]; self.timer=timer; } } //如果连接失败,5秒后重新连接 -(void)reconnectServer{ self.pushCount=0; self.reconnectCount=0; //连接失败重新连接 NSError*error=nil; [self.socketconnectToHost:SocketHostonPort:SocketPorterror:&error]; if(error){ DLog(@"SocektConnectError:%@",error); } } #pragmamark断开连接 //切断连接 -(void)cutOffSocket{ DLog(@"socket断开连接"); self.pushCount=0; self.reconnectCount=0; [self.timerinvalidate]; self.timer=nil; [self.socketdisconnect]; } @end
以上这篇iOS使用GCDSocketManager实现长连接的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。