我假設對於只有1字節(字符)的消息,我將直接使用read()和write()。通過套接字發送和接收字符串的子函數
對於那些大小大於1字節的消息,我使用兩個子函數來讀寫套接字。
例如,我有服務器構造一個名爲strcities(城市列表)的字符串並將其打印出來 - >沒有什麼奇怪的。然後將該字符串的字節數發送到客戶端,然後發送實際的字符串。
客戶端首先會讀取字節數,然後是實際的城市列表。
出於某種原因,我的代碼有時可以工作,有時不會。如果它有效,它還會打印出一些額外的字符,我不知道它們來自哪裏。如果沒有,它會掛起並永遠在客戶端等待,而服務器則返回到循環的頂部並等待來自客戶端的下一個命令。你能否看看我的代碼下面,讓我知道我做錯了什麼?
Attempt_read
string attempt_read(int rbytes) { // rbytes = number of bytes of message to be read
int count1, bytes_read;
char buffer[rbytes+1];
bool notdone = true;
count1 = read(sd, buffer, rbytes);
while (notdone) {
if (count1 == -1){
perror("Error on write call");
exit(1);
}
else if (count1 < rbytes) {
rbytes = rbytes - count1; // update remaining bytes to be read
count1 = read(sd, buffer, rbytes);
}
else {notdone = false;}
} // end while
string returnme;
returnme = string(buffer);
return returnme;
}
Attempt_write
void attempt_write(string input1, int wbytes) { // wbytes = number of bytes of message
int count1;
bool notdone = true;
count1 = write(sd, input1.c_str(), wbytes);
while (notdone) {
if (count1 == -1){
perror("Error on write call");
exit(1);
}
else if (count1 < wbytes) {
wbytes = wbytes - count1;
count1 = write(sd, input1.c_str(), wbytes);
}
else {notdone = false;}
} // end while
return;
}
嗯,我確實編寫和編譯的C++代碼,以便這就是爲什麼我想我添加了標籤C++ – rustyengineer 2014-12-06 16:57:20
這是一個項目的分配和選擇是C,C++和Java。我們選擇C++ – rustyengineer 2014-12-06 17:02:44
是的,我們很清楚這一點。但我想這就是我們選擇的,所以我們必須繼續它 – rustyengineer 2014-12-06 17:05:32