2015-04-02 59 views
0

我在服务器和客户端之间编写2个整数,它在两者之间混乱。客户端写道:读写系统调用返回乱码(C)

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”吗?

+1

你需要从'write'检查返回值和'read'以确保他们实际上工作,并且'read'实际上有3个字节。 – user3386109 2015-04-02 07:30:56

+0

我已经设置了一切条件,如if(写(socket2,playerMove,4)<0){perror(“写入失败”); \t}没有出现在终端 – REALLYANGRYSTUDENT 2015-04-02 07:36:25

回答

0

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

此外,在客户端,根据此处的代码,playerMove使用未经初始化。为了避免这种情况,总是提供建议并且提供一个很好的练习来初始化自动局部变量。

+0

我试图将其更改为4,我得到 这是对手的举动: 这是空白。我是否需要更改读取和写入的字节数? – REALLYANGRYSTUDENT 2015-04-02 07:28:00

+0

@REALLYANGRYSTUDENT是的。你正在设置值“3 1”? – 2015-04-02 07:29:52

+0

我试过,它仍然是空的 3 1使用fgets从标准输入中检索。代码是 printf(“Enter your move:\ n”); fgets(playerMove,4,stdin); – REALLYANGRYSTUDENT 2015-04-02 07:30:55

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

我也建议长期使用4个字节的缓冲区,通过Sourav戈什指出

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