1

I tried to connect to the server and send some information to the server(like username, password..), and the server send me back the ID (string type). The problem is I can not get the ID. Could anyone help me? I am beginner in IOS coding. Thanks.

Here is the codes:

  1. After I click the button, it will call my own function to get serverIP which is a string and Port which is a int.
  2. Then that function will call this function to connect the server:

    (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];
    }
    
4

1 に答える 1

4

サーバーの実装についてはわかりませんが、ほとんどの実装では、リクエストを処理する前に最初の改行文字まで読み取ります。

したがって、最後[DataPassToServer dataUsingEncoding:NSUTF8StringEncoding]に改行文字("\n")が含まれていることを確認してください。

あなたのコードはうまく見えて、私のために働きます。

于 2012-09-07T09:26:34.153 に答える