我编写了一个客户端/服务器应用程序,其中服务器根据客户端的请求生成多个线程。
这些线程应该向客户端发送一些数据(字符串)。
问题是,数据在客户端被覆盖。我该如何解决这个问题?
我已经阅读过类似问题的其他一些主题但无法找到确切的解决方案。
以下是我接收数据的客户端代码。
while(1)
{
char buff[MAX_BUFF];
int bytes_read = read(sd,buff,MAX_BUFF);
if(bytes_read == 0)
{
break;
}
else if(bytes_read > 0)
{
if(buff[bytes_read-1]=='$')
{
buff[bytes_read-1]='\0';
cout<<buff;
}
else
{
cout<<buff;
}
}
}
服务器线程代码:
void send_data(int sd,char *data)
{
write(sd,data,strlen(data));
cout<<data;
}
void *calcWordCount(void *arg)
{
tdata *tmp = (tdata *)arg;
string line = tmp->line;
string s = tmp->arg;
int sd = tmp->sd_c;
int line_no = tmp->line_no;
int startpos = 0;
int finds = 0;
while ((startpos = line.find(s, startpos)) != std::string::npos)
{
++finds;
startpos+=1;
pthread_mutex_lock(&myMux);
tcount++;
pthread_mutex_unlock(&myMux);
}
pthread_mutex_lock(&mapMux);
int t=wcount[s];
wcount[s]=t+finds;
pthread_mutex_unlock(&mapMux);
char buff[MAX_BUFF];
sprintf(buff,"%s",s.c_str());
sprintf(buff+strlen(buff),"%s"," occured ");
sprintf(buff+strlen(buff),"%d",finds);
sprintf(buff+strlen(buff),"%s"," times on line ");
sprintf(buff+strlen(buff),"%d",line_no);
sprintf(buff+strlen(buff),"\n",strlen("\n"));
send_data(sd,buff);
delete (tdata*)arg;
}
答案 0 :(得分:3)
作为补充说明:不能依赖于read()
/ write()
读/写字节数,因为这两个函数被告知读/写。检查它们的返回值以了解这些函数实际读取/写入的字节数并循环它们是非常必要的,直到读取/写入所有要读/写的数据为止。
答案 1 :(得分:-1)