我正在尝试从服务器接收数据,并且第一次可以正常工作,但是由于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);
当服务器发送一次数据并关闭套接字时,它可以正常工作。但是然后我让客户端再次打开套接字,将数据发送到服务器,服务器将再次向客户端发送数据并关闭套接字。客户端将再次尝试读取服务器发送的数据,但这一次它将新信息和部分旧信息填充到接收中
最佳答案
在我看来,在您的代码中您先删除了接收到的数据,然后再打印它-然后您将一个字符串传递给printf
,该字符串基本上是空的,并且我不确定printf
会做什么(因为它是格式化的)空的字符串)。
试试这个:
int nread;
while((nread = read(client_sock_desc, receive, sizeof(receive)-1)) > 0) {
receive[nread]='\0'; // explicit null termination: updated based on comments
printf("%s\n",receive); // print the current receive buffer with a newline
fflush(stdout); // make sure everything makes it to the output
receive[0]='\0'; // clear the buffer : I am 99% sure this is not needed now
}