我正在創建一個聊天應用程序,其中兩個程序(聊天服務和聊天客戶端)來回發送消息。 我試圖設置它一次發送一個字符。我計算消息應該多長時間,並將聊天服務發送給聊天客戶端。數字傳輸沒有問題,但是當我嘗試讀取/寫入消息時,使用打印語句成功發送了指示for循環應該結束的打印語句,但在發送最後一個字母后,程序只是掛起。連續發送/接收的消息的打印消息從不被觸發。但是,如果Sig INT聊天客戶端同時掛起聊天服務似乎完成其寫入並顯示完成發送消息。我對正在發生的事情感到有點不知所措。從我的打印語句看來,for循環看起來應該滿足條件,但程序似乎都陷入其中。用於讀寫循環的C套接字問題
即時通訊服務: 上面顯示的代碼中,我將「Tom:」作爲主處理程序硬編碼,並將hostmessage的用戶輸入作爲本例中的測試對象。 MONE是程序的
char mone[2]="";
//send message to chatclient
charcount= strlen(hostmessage);
meslen=charcount+strlen(hosthandle);//total message length
int number_to_send = meslen;
int converted_number = htonl(number_to_send);
write(newsockfd, &converted_number, sizeof(converted_number)); //sends number to chat client
for (j=0;j<strlen(hosthandle);j++)
{
mone[0]=hosthandle[j];
n = write(newsockfd, mone, 2); //writes handle to chatclient
if (n <= 0)
{
perror("Message not \n");
}
printf("%s %d \n",mone, j);
}
for (j=0;j<strlen(hostmessage);j++)
{
mone[0]=hostmessage[j];
n = write(newsockfd, mone, 2); //writes message to chatclient
printf("%s %d \n",mone, j);
}
printf("Finished Sending Message");
輸出(hostmessage是測試消息大小= 8)
文稿:
Tom: test
T 0
o 1
m 2
: 3
t 0
e 1
s 2
t 3
ChatClient
int received_int = 0; //this section of code receives message length from chatserve
int return_status = read(sockfd, &received_int, sizeof(received_int));
if (return_status > 0) {
fprintf(stdout, "Received int = %d\n", ntohl(received_int));
}
else
{
printf("did not receive message length");
}
for(j=0;j<received_int;j++)
{
n=read(sockfd,kone,2); //reads in letter from chat serve
if (n <= 0)
{
perror("Message not recieved\n");
}
//printf("%d \n", n);
printf("%s %d \n",kone, j);
}
printf("Received message \n");
輸出程序的在此之後它只是掛起當我覺得這兩個循環應該打到他們的櫃檯。
Received int = 8
T 0
o 1
m 2
: 3
t 4
e 5
s 6
t 7
慣例:未能正確完整地處理read()返回的結果。當傳遞的參數不保證以空字符結尾時,調用期望以空字符結尾的字符數組的函數。 –
則可能會遇到一個問題:爲'(j = 0;Ĵ
Aconcagua