1

クライアントに引数として文字列を渡す際に問題があり、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);

サーバーによって出力されるメッセージは次のとおりです。

ここに画像の説明を入力

誰かこれで手を貸してくれませんか。

ありがとうございました

4

1 に答える 1

2

バッファ ch[] は null で終了していません。また、一度に 1 バイトしか読み取っていないため、そのバッファーの残りはガベージ文字です。また、読み取り呼び出しに &ch を渡すことを使用していますが、配列は既にポインターであるため、&ch == ch.

少なくとも、コードは次のようにする必要があります。

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

ただし、一度に1バイトしか読み取らないため、一度に1文字しか出力されません。これはより良いでしょう:

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
}
于 2013-03-14T01:59:15.130 に答える