2015-04-02 60 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