5

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

}

请参阅上面代码中的注释。

当我断开 Wificonnecttohost时返回yes。我不知道问题出在哪里。任何人都可以帮助我并给我一些指示吗?

4

1 回答 1

2

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

- (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;
}
于 2012-11-28T09:28:43.273 回答