我已经在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];

}

请查看上面代码中的注释。

当我断开Wifi connecttohost的连接时,请返回yes。我不知道问题出在哪里。谁能帮助我,给我一些指导?

最佳答案

由于某种原因,在这种情况下connectToHost将始终返回true。您需要依赖委托(delegate)方法。

- (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;
}

10-08 07:47