我有一个交换消息的客户端/服务器,我试图在字符串的开头添加我发送的字符串的大小,以便服务器知道要读取多少字节。我从 char* 的 +4 pos 开始添加消息,并使用 memcpy 复制字符串的 strlen。它似乎不起作用,并且有些东西告诉我它的错误方法。这是我的代码。
//*CLIENT*//
send_message = malloc(1024 * sizeof(char));
strcpy(send_message + 4,"GETFILES ");
strcat(send_message,"/");
strcat(send_message,directory_name);
size = strlen(send_message) + 1;
csize = malloc(4 * sizeof(char));
csize = (char*)&size;
memcpy(&send_message,csize,4);
if((sent = send(sock, send_message, strlen(send_message) + 1, 0)) < 0)
perror("write");
//*SERVER*//
while(1){
count = recv(events[i].data.fd, buf, sizeof(buf),0);
if(count == -1){
//if errno = EAGAIN we have read all data. going back to main loop
if(errno != EAGAIN){
perror("read");
done = 1;
}
break;
}
else if(count == 0){
//End of file. The remote has closed the connections
done = 1;
break;
}
printf("received message %s and count %d\n", buf, count);
}
如果我评论这些行
csize = malloc(4 * sizeof(char));
csize = (char*)&size;
memcpy(send_message,csize,4);
我得到这个输出:
received message ▒�w�GETFILES /test and count 19
否则我没有输出..任何想法如何修复它并添加标题以便我的服务器提前知道要读取多少字节?