读写系统调用返回乱码(C)

时间:2015-04-02 07:21:45

标签: c client system server

我在服务器和客户端之间编写了2个整数,并且它之间发生了混乱。客户写道:

char playerMove[3];
char oppMove[3];
write(sock, playerMove, 3);
printf("Waiting on Opponent's move.\n");
read(sock, oppMove, 3);
printf("this was Opponent's move: %s\n", oppMove);

,而相关的服务器代码是

char playerMove[3];
read(socket1, playerMove, 3);
printf("First move is: %s", playerMove);

write(socket2, playerMove, 3);

终端显示客户端说

Waiting on Opponent's move.
this was Opponent's move: �D�K

但是在服务器的终端,我可以清楚地看到它正常运行

First move is: 3 1

有人可以帮助我吗?我是C的新手。我需要做一些特别的事情来编写" 3 1"给我的客户?

3 个答案:

答案 0 :(得分:0)

您的3元素char数组太小,无法处理格式" 3 1"的字符串输入。您还需要一个元素来存储终止空值。

此外,在客户端,根据此处的代码,playerMove未经初始化使用。为了避免这种情况,我们始终建议并将自动局部变量初始化。

答案 1 :(得分:0)

尝试以下内容。缓冲区 oppMove 在使用前设置为0。

char playerMove[3];
char oppMove[3];
memset(oppMove,'\0',3);
write(sock, playerMove, 3);
printf("Waiting on Opponent's move.\n");
read(sock, oppMove, 3);
printf("this was Opponent's move: %s\n", oppMove);

我还建议使用Sourav Ghosh指出的4字节长的缓冲区

答案 2 :(得分:0)

Read and write do not automatically append a NUL termination byte.
so do not expect them.

However there are a few problems with the code.

1) player move is not initialized, so trash is sent to the server.
2) the returned values from write and read should be checked 
   to assure the operations are successjul
3) the client call to printf is using '%s' which is expecting a 
   NUL terminated string,  however the value read is just some
   3 random characters (because the sent value was just some random characters.
suggestions:
1) initialize the player move array to some known value
2) in the printf() format string use '%c%c%c'  Not '%s'

regarding the server code.
it is totally random the something printable was displayed on the terminal
especially since the value read (and the buffer read into) 
is not NUL terminated.
the call to printf has the same problem with the format string
and needs the same fix as the client call to printf
相关问题