Reputation: 191
I have tested this code on an iPad:
// execute the function when press button
- (IBAction)connect:(id)sender {
//[super viewDidLoad];
AsyncSocket *socket1=[[AsyncSocket alloc] initWithDelegate:self];
BOOL pass = [socket1 connectToHost:@"www.126.com" onPort:80 error:nil]; // but when I break the wifi,connecttohost still return yes
if(pass)
{
[connectbtn setTitle:@"connected" forState:UIControlStateNormal];
}
[socket1 readDataWithTimeout:3 tag:1];
[socket1 writeData:[@"GET / HTTP/1.1\n\n" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:3 tag:1];
}
Please see the comments in the code above.
When I disconnect the Wifi connecttohost
return yes
. I don't know where the problem is. Could anyone help me and give me some pointers?
Upvotes: 5
Views: 313
Reputation: 11297
For some reason connectToHost will always return true in this case. You need to rely on the delegate methods.
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
NSLog(@"Connected To %@:%i.", host, port);
}
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err {
NSLog(@"Disconnecting. Error: %@", [err localizedDescription]);
}
- (void)onSocketDidDisconnect:(AsyncSocket *)sock {
NSLog(@"Disconnected.");
[socket setDelegate:nil];
[socket release];
socket = nil;
}
- (BOOL)onSocketWillConnect:(AsyncSocket *)sock {
NSLog(@"onSocketWillConnect:");
return YES;
}
Upvotes: 2