2

我正在使用 asyncsocket 创建与目标 C 的套接字连接。我使用“connectToHost”方法执行此操作。我正在尝试处理套接字连接失败的情况。“connectToHost”应该在连接成功时返回“YES”,否则返回 NO。出于某种原因,它总是返回“是”。我什至提供了一个空白字符串作为主机,它仍然返回是。有什么想法吗?

谢谢,

罗宾

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);
}
4

1 回答 1

6

根据头文件

// 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:".

如果您查看源代码——出于对所有神圣事物的热爱,在使用开源软件时,请使用源代码!–,您将看到您正在调用的方法NO仅在无法启动连接过程时才返回。返回值YES只是说,“好的,我正在尝试连接:

  • “如果出现问题,我会打电话通知你onSocket:willDisconnectWithError:onSocketDidDisconnect:
  • “如果一切顺利,你会收到一条onSocket:didConnectToHost:port:消息,嗯?”

不要期望来自异步套接字库的同步行为。

于 2011-04-06T22:31:52.100 回答