我正在尝试从服务器接收数据,它第一次工作正常,但随着 read() 不断循环,它也会存储它之前读取的旧值。这是我到目前为止所拥有的。
char receive[50];
if((he = gethostbyname(servername)) == NULL ) {
perror(strcat("Cannot find server named:", servername));
exit(0);
}
he = gethostbyname("localhost");
localIP = inet_ntoa(*(struct in_addr *)*he->h_addr_list);
client_sock_desc = socket(AF_INET, SOCK_STREAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(localIP);
server_addr.sin_port = htons(serverport);
len = sizeof(server_addr);
if(connect(client_sock_desc, (struct sockaddr *)&server_addr,len) == -1) {
perror("Client failed to connect");
exit(0);
}
strcpy(buf, "CLIENT/REQUEST\n");
send(client_sock_desc, buf, strlen(buf), 0);
//send actual function request
//put a space before \n char to make it easier for the server
for(i = 0; i < sizeof(wholeRequest); i++) {
if(wholeRequest[i] == '\n') {
wholeRequest[i] = ' ';
wholeRequest[i+1] = '\n';
break;
}
}
while(read(client_sock_desc, receive, sizeof(receive)) > 0) {
strcpy(receive, ""); //attempt to erase all old values
printf(receive);
fflush(stdout);
}
close(client_sock_desc);
当服务器发送一次数据并关闭套接字时,它可以完美地工作。但后来我让客户端再次打开套接字,向服务器发送数据,服务器将再次向客户端发送数据并关闭套接字。客户端将再次尝试读取服务器发送的数据,但这一次它用新信息和部分旧信息填充接收