Reputation: 737
I am creating a socket connection with objective C, using asyncsocket. I do this using the "connectToHost" method. I am trying to handle the case where the socket connection fails. "connectToHost" is supposed to return "YES" when it connects sucessfully, and a NO otherwise. For some reason, it is always returning a yes. I even supplied a blank string as the host and it still returns yes. Any thoughts?
Thanks,
Robin
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);
}
Upvotes: 2
Views: 2025
Reputation: 36143
Per the 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:".
If you check the source – for the love of all things holy, when working with open source software, USE THE SOURCE! –, you will see that the method you are invoking returns NO
only when it fails to start the connection process. A return value of YES
just says, "Okay, I'm trying to connect:
onSocket:willDisconnectWithError:
and onSocketDidDisconnect:
.onSocket:didConnectToHost:port:
message, mmkay?"Don't expect synchronous behavior from an asynchronous socket library.
Upvotes: 6