我必须使用 UDP 进行服务器-客户端文件传输。我创建了一个接收客户端发送的消息的基本服务器。就这样。现在是主要部分:-
1. The message sent by client is the name of file .
2. Now the server checks whether there exists this file or not .
3. If there exists it sends the file to the client and it also keeps the count of the number of requests of file made by the client .
我是新手,我不知道如何进一步进行。
这是服务器代码
#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[2000];
char file_buffer[2000];
int sd,connfd,len;
struct sockaddr_in servaddr,cliaddr;
sd = socket(AF_INET, SOCK_DGRAM, 0);
if(sd==-1)
{
printf(" socket not created in server\n");
exit(0);
}
else
{
printf("socket created in server\n");
}
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 )
printf("Not binded\n");
else
printf("Binded\n");
len=sizeof(cliaddr);
recvfrom(sd,buff,1024,0,
(struct sockaddr *)&cliaddr, &len);
printf("%s\n",buff);
/* */
FILE *fp;
fp=fopen(buff,"r");
if(fp==NULL)
{
printf("file does not exist\n");
}
fseek(fp,0,SEEK_END);
size_t file_size=ftell(fp);
fseek(fp,0,SEEK_SET);
if(fread(file_buffer,file_size,1,fp)<=0)
{
printf("unable to copy file into buffer\n");
exit(1);
}
if(sendto(sd,file_buffer,strlen(file_buffer),0, (struct sockaddr *)&cliaddr, &len)<0) {
printf("error in sending the file\n");
exit(1);
}
bzero(file_buffer,sizeof(file_buffer));
/* */
close(sd);
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()
{
char buff[2000];
int sockfd,connfd,len;
struct sockaddr_in servaddr,cliaddr;
// create socket in client side
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd==-1)
{
printf(" socket not created in client\n");
exit(0);
}
else
{
printf("socket created in client\n");
}
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
printf("Type ur UDP client message\n");
scanf("%s",buff);
// send msg to server
sendto(sockfd, buff, strlen(buff), 0,
(struct sockaddr *)&servaddr, sizeof(struct sockaddr));
char file_buffer[2000];
if (recvfrom(sockfd,file_buffer,2000,0, (struct sockaddr *)&servaddr, sizeof(struct sockaddr))<0)
{
printf("error in recieving the file\n");
exit(1);
}
char new_file[]="copied";
strcat(new_file,buff);
FILE *fp;
fp=fopen(new_file,"w+");
if(fwrite(file_buffer,1,sizeof(file_buffer),fp)<0)
{
printf("error writting file\n");
exit(1);
}
//close client side connection
close(sockfd);
return(0);
}
我已经编辑了程序并创建了一个新的缓冲区 file_buffer ,服务器从文件中读取数据并将其写入并发送到客户端,另一端客户端接收数据并复制该文件并写入其中。但是在编译时它会在写入文件时出错:(