我在服务器和客户端之间写入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”?

最佳答案

尝试以下类似的方法。在使用之前,将缓冲区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字节长的缓冲区

08-19 17:57