在AsyncSocket类中调用connecttohost

Swe*_*ady 5 iphone ipad

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

}
Run Code Online (Sandbox Code Playgroud)

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

当我断开Wifi connecttohost返回时yes.我不知道问题出在哪里.谁能帮助我并给我一些指示?

Soh*_*aib 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;
}
Run Code Online (Sandbox Code Playgroud)