2013-03-14 70 views
1

我有一個將字符串作爲參數傳遞給我的客戶端的問題,而我對C來說是新的,因此無法真正弄清楚發生了什麼。我設法將一個角色傳遞給服務器,但遇到了字符串問題。這個代碼表示從我的服務器主循環:C語言。 TCP服務器客戶端,字符串傳遞錯誤

while(1) 
{ 
    char ch[256]; 
    printf("server waiting\n"); 

    rc = read(client_sockfd, &ch, 1); 
    printf("The message is: %s\n", ch); 
    write(client_sockfd, &ch, 1); 
    break; 
} 

客戶端代碼:

char ch[256] = "Test"; 

rc = write(sockfd, &ch, 1); 

通過服務器打印的消息如下:

enter image description here

能有人給我用這個手。

謝謝

回答

2

您的緩衝區ch []不是空終止。而且,由於您一次只讀取1個字節,該緩衝區的其餘部分就是垃圾字符。另外,您正在使用傳遞& ch來讀取調用,但數組已經是指針,所以& ch == ch。

最起碼的代碼需要看起來像這樣:

rc = read(client_sockfd, ch, 1); 
    if (rc >= 0) 
    { 
     ch[rc] = '\0'; 
    } 

但是,這隻會在同一時間,因爲你只能讀一次一個字節打印一個字符。這會更好:

while(1) 
{ 
    char buffer[256+1]; // +1 so we can always null terminate the buffer appropriately and safely before printing. 
    printf("server waiting\n"); 

    rc = read(client_sockfd, buffer, 256); 
    if (rc <= 0) 
    { 
     break; // error or remote socket closed 
    } 
    buffer[rc] = '\0'; 

    printf("The message is: %s\n", buffer); // this should print the buffer just fine 
    write(client_sockfd, buffer, rc); // echo back exactly the message that was just received 

    break; // If you remove this line, the code will continue to fetch new bytes and echo them out 
}