didConnectToHost没有被调用

时间:2012-08-25 09:56:12

标签: objective-c ios cocoa gcdasyncsocket

我使用GCDAsyncSocket并导入CGDAsyncSocket.h创建了一个名为“NetClass”的类的客户端。 比我的LoginViewController我调用我的网络类功能连接到服务器。

在服务器端,我看到客户端已连接,但客户端didConnectToHost未被调用。

NetClass中的LoginViewController来电:

NetClass *nc = [[NetClass alloc] init];
    [nc ReceiveData:ip login:login password:md5 ];

我的NetClass功能:

- (BOOL)ReceiveData:(NSString *)ip login:(NSString*)login password:(NSString*)password
{
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    asyncSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:mainQueue];

    NSError *error = nil;
    uint16_t port = 2012;
    if (![asyncSocket connectToHost:ip onPort:port error:&error])
    {
        NSLog(@"Error connecting: %@", error);
        return NO;
    }
    else
    {
        NSLog(@"%@",asyncSocket.connectedHost);
        NSData *data = [[NSString stringWithFormat:@"<MOBIL><refreshall>TRUE</refreshall><user>%@</user><password>%@</password>",@"tst",@"tsts"] dataUsingEncoding:NSASCIIStringEncoding];
        NSData *enddata = [[NSString stringWithFormat:@"</ddodata"] dataUsingEncoding:NSASCIIStringEncoding];
        [asyncSocket writeData:data withTimeout:-1 tag:1];
        [asyncSocket readDataToData:enddata  withTimeout:-1 maxLength:-1 tag:1];
        [asyncSocket disconnect];
        return YES;
    }


}
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"%@ %@",@"CONNECTED TO HOST",host);
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    NSLog(@"socketDidDiscoffffnnect:%p withError: %@", sock, err);
}

但同时函数socketDidDisconnect被调用

NSLog输出:

  2012-08-25 14:16:46.312 TacticalView[34981:f803] (null)
2012-08-25 14:16:46.313 TacticalView[34981:f803] socketDidDiscoffffnnect:0x88024d0 withError: (null)

我看到asyncSocket在更改ReceiveData时没有连接:

 if (![asyncSocket connectToHost:ip onPort:port error:&error])
    {
        NSLog(@"Error connecting: %@", error);
        return NO;
    }
    else
    {
        if ([asyncSocket isConnected])
        {

        NSData *data = [[NSString stringWithFormat:@"<MOBIL><refreshall>TRUE</refreshall><user>%@</user><password>%@</password>",@"tst",@"tsts"] dataUsingEncoding:NSASCIIStringEncoding];

        NSData *enddata = [[NSString stringWithFormat:@"</ddodata"] dataUsingEncoding:NSASCIIStringEncoding];

        [asyncSocket writeData:data withTimeout:-1 tag:1];
        [asyncSocket readDataToData:enddata  withTimeout:-1 maxLength:-1 tag:1];
        [asyncSocket disconnect];
        }
        return YES;
    }

如果我在我的LoginViewController中创建套接字,则didConnectToHost方法正在调用/什么是错误的&amp;为什么我不能在我的NetClass中使用此方法?

1 个答案:

答案 0 :(得分:0)

众所周知,GCDAsyncSocket不会调用didConnectToHost:方法。我建议使用AsyncSocket或自己调用委托方法。

相关问题