GCDAsyncSocket 尝试通过不同端口连接服务器的解决方案

原先的设计是通过hostname和port来建立连接的:

[_asyncSocket connectToHost:hostname onPort:_host_port error:&err]

但是有这么一种情况,就是服务端有时候会把port改变掉,比如说它本来约定是用8001的,但是有时候进程被意外杀死之后,8001这个port就申请不到了,只好用8002这个端口,那么在客户端是不知道的,因此要求客户端在连接服务器时,先尝试用8001去连接,假如连接不成功,则改为用8002去连接。

这里面有一个难题,就是在GCDAsyncSocket的connectToHost这个方法里,不能马上知道成功或者失败,因为它的执行是非阻塞的,它通常会先返回成功,即使将来它会连不上,那么它连不上时会不会通过别的delegation来通知用户呢?

为了这个问题,特别研究了一下它里面的实现流程:

- (void)closeWithError:(NSError *)error

这个方法里面有:
// If the client has passed the connect/accept method, then the connection has at least begun.
	// Notify delegate that it is now ending.
	BOOL shouldCallDelegate = (flags & kSocketStarted) ? YES : NO;
	BOOL isDeallocating = (flags & kDealloc) ? YES : NO;
	
	// Clear stored socket info and all flags (config remains as is)
	socketFDBytesAvailable = 0;
	flags = 0;
	sslWriteCachedLength = 0;
	
	if (shouldCallDelegate)
	{
		__strong id theDelegate = delegate;
		__strong id theSelf = isDeallocating ? nil : self;
		
		if (delegateQueue && [theDelegate respondsToSelector: @selector(socketDidDisconnect:withError:)])
		{
			dispatch_async(delegateQueue, ^{ @autoreleasepool {
				
				[theDelegate socketDidDisconnect:theSelf withError:error];
			}});
		}	
	}


从这里可以看到,当连接失败时,它会呼叫
socketDidDisconnect:withError:

这个代理方法的,因此解决的方案就出来了,可以实现这个方法,然后再在里面重新用新的端口来建立连接

-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    
    
    NSLog(@"socketDidDisconnect port:%d:%@",[sock localPort],err);
    
    为了谨慎起见,只处理错误号为61的情况
    if (err.code == 61) { //hu:handle port change to 8002
        NSLog(@"connection refused");
        _host_port = 8002;
        [self connectServer];
    }
}

经过试验,这样的方式是可行的。




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值