我正在编写一个简单的客户端 - 服务器程序。我的服务器使用telnet工作正常,但我的客户端只能发送字节,而不是接收它们。我有什么明显的遗失吗?我想这可能是因为我以某种方式使用了recv
功能,但这对我来说并不明显。 recv
函数始终获得0个字节。我应该补充一点,recv函数不会阻塞,但收到的字节数总是为零。
客户端主要功能中的代码片段如下所示。函数changeIPOrPort
设置服务器的IP地址和端口,并且由于服务器收到客户端消息,因此工作正常。如有必要,我也可以发布服务器代码。
int main() {
int client_fd, numbytes = 0;
//int quit = 0;
struct sockaddr_in their_addr;
char response[MAXDATASIZE] = "";
char buf[MAXDATASIZE] = "";
size_t len = 0;
/* Server config*/
their_addr.sin_family = AF_INET;
memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);
printf("Configuring the server\n");
changeIPOrPort(&their_addr);
printf("Hello! please input letters to know things about me.\n");
printf("Each character will give you a piece of information about me\n");
printf("%s\n", serviceInfo); //info string "UI"...
/*create client socket*/
client_fd = socket(AF_INET, SOCK_STREAM, 0);
if(connect(client_fd, (struct sockaddr *)&their_addr, sizeof(their_addr)) < 0) {
printf("\n Error : Connect Failed \n");
return 1;
}
if(!fgets(response, sizeof (response), stdin)) {
printf("Error reading line.\n");
}
else {
len = strlen(response);
if(response[len - 1] == '\n') {
response[len - 1] = '\0';
}
printf("You entered the characters:%s\n", response);
printf("sending...\n");
send(client_fd, response, len, 0);
numbytes = recv(client_fd, buf, strlen(buf), 0) ;
if(numbytes < 0) {
printf("Error receiving from server, quitting\n");
exit(1);
}
else {
printf("Number of bytes received: %d\n", numbytes);
buf[numbytes] = '\0';
printf("%s\n", buf);
printf("This is errno\n", errno);
}
}
close(client_fd);
return 0;
}
答案 0 :(得分:2)
将'strlen(buf)'替换为'sizeof(buf)-1'