我正在使用asyncsocket创建一个带有目标C的套接字连接。我使用“connectToHost”方法执行此操作。我试图处理套接字连接失败的情况。当连接成功时,“connectToHost”应该返回“YES”,否则返回NO。出于某种原因,它总是返回是。我甚至提供了一个空字符串作为主机,它仍然返回yes。有什么想法吗?
谢谢,
罗宾
BOOL connectStatus = NO; //used to check if connection attempt succeeded
testSocket = [[AsyncSocket alloc] initWithDelegate: self];
connectStatus = [testSocket connectToHost: @"" onPort: 5000 error: nil];
if(connectStatus == NO)
{
NSLog(@"Failed to connect to socket ");
}
else {
NSLog(@"Connected to socket sucessfully, connectStatus = %d", connectStatus);
}
答案 0 :(得分:6)
根据header file:
// Once one of the accept or connect methods are called, the AsyncSocket instance is locked in
// and the other accept/connect methods can't be called without disconnecting the socket first.
// If the attempt fails or times out, these methods either return NO or
// call "onSocket:willDisconnectWithError:" and "onSockedDidDisconnect:".
如果你检查the source - 对所有神圣事物的热爱,在使用开源软件使用资源! - 时,你会看到你调用的方法返回NO
仅在无法启动连接过程时。返回值YES
只是说,“好吧,我正在尝试连接:
onSocket:willDisconnectWithError:
和onSocketDidDisconnect:
告诉您。onSocket:didConnectToHost:port:
消息,mmkay?”不要指望来自异步套接字库的同步行为。