Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call connecttohost in AsyncSocket class

Tags:

iphone

ipad

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?

like image 896
Sweet Lady Avatar asked Nov 04 '22 10:11

Sweet Lady


1 Answers

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;
}
like image 168
Sohaib Avatar answered Nov 12 '22 21:11

Sohaib