无法使用GCDAsyncSocket从服务器读取数据

时间:2012-09-07 00:15:28

标签: ios cocoa networking gcdasyncsocket

我尝试连接到服务器并向服务器发送一些信息(如用户名,密码..),然后服务器将ID发回给我(字符串类型)。问题是我无法获取ID。谁能帮助我?我是IOS编码的初学者。感谢。

以下是代码:

  1. 点击按钮后,它会调用我自己的函数来获取serverIP,这是一个字符串,而端口是一个int。
  2. 然后该函数将调用此函数来连接服务器:

    (void)logInCheck {
    
        asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];   
        NSError *error = nil;
        uint16_t port = serverPort;
    
        if (![asyncSocket connectToHost:serverIP onPort:port error:&error])
        {
            DDLogError(@"Unable to connect to due to invalid configuration: %@", error);
        }
        else
        {
            DDLogVerbose(@"Connecting...");
            [self passDataToServer];
        }
    }
    
    //DataPassToServer is a NSString that hold my data
    
    (void)passDataToServer
    {
        NSData *requestData = [DataPassToServer dataUsingEncoding:NSUTF8StringEncoding];
        [asyncSocket writeData:requestData withTimeout:-1.0 tag:0];
        [asyncSocket readDataWithTimeout:-1 tag:0];
    }
    
    //this function call successfully
    
    -(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
    {
        DDLogVerbose(@"socket:didConnectToHost:%@ port:%hu", host, port);
    }
    
    //this function call successfully
    
    (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
    {
        DDLogVerbose(@"socket:didWriteDataWithTag:");
    }
    
    //This function does not run !!! Nothing print out. 
    
    (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
    {
        DDLogVerbose(@"socket:didReadData:withTag:");
        NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"ID = %@",response);
        [asyncSocket readDataWithTimeout:-1 tag:0];
    }
    

1 个答案:

答案 0 :(得分:4)

我不了解您的服务器实现,但是大多数实现在处理请求之前会读取第一个换行符。

因此,请确保您的[DataPassToServer dataUsingEncoding:NSUTF8StringEncoding]最后包含换行符("\n")。

您的代码看起来很好,适合我。