我正在尝试实现一个服务器客户端应用程序,其中客户端将文件名发送到服务器。服务器查找文件,如果文件存在,则将文件发送回客户端,然后继续。这是我写的代码,但问题是服务器没有将文件内容发送回客户端我之前遇到同样的问题,然后我重新编写了代码。
以下是代码: -
服务器端
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <string.h>
int main() {
char buff[20];
char content[200];
int sd, connfd, len, bytes_read;
struct sockaddr_in servaddr, cliaddr;
sd = socket(AF_INET, SOCK_DGRAM, 0);
if (sd == -1) {
puts("socket not created in server");
return 1;
} else {
puts("socket created in server");
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(7802);
if (bind(sd, (struct sockaddr *)&servaddr, sizeof(servaddr)) != 0) {
puts("Not binded");
return 1;
} else {
puts("Binded");
}
len = sizeof(cliaddr);
recvfrom(sd, buff, 1024, 0, (struct sockaddr *)&cliaddr, &len);
printf("%s\n", buff);
FILE *fp = fopen(buff, "r");
if (fp == NULL) {
printf("File does not exist \n");
return 1;
}
while (1) {
bytes_read = read(fp, content, sizeof(content));
if (bytes_read == 0)
break;
sendto(sd, content, sizeof(content), 0, (struct sockaddr*)&cliaddr, len);
bzero(content, 200);
}
strcpy(content, "end");
sendto(sd, content, sizeof(content), 0, (struct sockaddr*)&cliaddr, len);
return 0;
}
客户方:
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netinet/in.h>
#include <sys/types.h>
int main() {
int count = 0;
char buff[20], output[20];
char file_buffer[200];
int sockfd, connfd, len;
struct sockaddr_in servaddr, cliaddr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1) {
puts("socket not created in client");
return 1;
} else {
puts("socket created in client");
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY; // ANY address or use specific address
servaddr.sin_port = htons(7802); // Port address
puts("Type your UDP client message");
scanf("%s", buff);
puts("enter the name of new file to be saved");
scanf("%s", output);
// send msg to server
sendto(sockfd, buff, strlen(buff) + 1, 0,
(struct sockaddr *)&servaddr, sizeof(struct sockaddr));
count++;
printf("%d\n", count);
FILE *fp = fopen(output, "a");
if (fp == NULL) {
puts("error in file handling");
return 1;
}
recvfrom(sockfd, file_buffer, sizeof(file_buffer), 0, NULL, NULL);
while (1) {
if (strcmp(file_buffer, "end") == 0)
break;
printf("%s", file_buffer);
write(fp, file_buffer, strlen(file_buffer));
bzero(file_buffer, 200);
recvfrom(sockfd, file_buffer, sizeof(file_buffer), 0, NULL, NULL);
}
puts("completed");
return 0;
}
答案 0 :(得分:1)
您可能应该在服务器端使用fread()
功能而不是read()
。
函数fopen()
和read()
是不同接口的一部分:
家庭阅读() - &gt;打开,关闭,读取,写入,ioctl(系统调用)
家庭恐惧() - &gt; fopen,fclose,fread,fwrite,fcntl(标准库)
我可以假设fopen()
给出的文件描述符与read()
期望的文件描述符不完全相同。
客户端也一样。您可以使用fopen()
打开文件并使用write()
进行编写。请使用fwrite()