簡體   English   中英

C語言。 TCP服務器客戶端,字符串傳遞錯誤

[英]C language. TCP server-client, string passing error

我在將字符串作為參數傳遞給客戶端時遇到問題,由於我是C語言的新手,所以無法真正弄清楚發生了什么。 我設法將一個字符傳遞給服務器,但是字符串出現問題。 這段代碼代表了我服務器的主循環:

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);

服務器打印的消息如下:

在此處輸入圖片說明

有人可以幫我這個忙嗎?

謝謝

您的緩沖區ch []不能為null終止。 並且由於您一次只讀取1個字節,因此該緩沖區的其余部分為垃圾字符。 另外,您正在使用將&ch傳遞給read調用,但是數組已經是指針,因此&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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM