我假设对于只有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