socket断开连接后,为了不给服务器造成连接压力,必须控制重新连接的频率。否则一旦服务器出现异常,而客户端又不断向服务器发送连接请求,势必会给服务器雪上加霜,甚至出现崩溃的情况!以下是为了防止此种弊端的控制代码(若有缺陷,还望指出):
- (void)socketDidDisconnect:(GCDAsyncSocket*)sock withError:(NSError*)err {
if(_reconnection_time>=0 && _reconnection_time <= kMaxReconnection_time) {
[_timer invalidate];
_timer=nil;
int time = 2;//这里设置重连时间,自己定夺
_timer= [NSTimer scheduledTimerWithTimeInterval:time target:selfselector:@selector(reconnection) userInfo:nil repeats:NO];
_reconnection_time++;
NSLog(@"socket did reconnection,after %ds try again",time);
}else{
_reconnection_time=0;
NSLog(@"socketDidDisconnect:%p withError: %@", sock, err);
}
}