#define DOWNLOAD "DOWNLOAD"
#define UPLOAD "UPLOAD"
#define YES "YES"
#define NO "NO"
#define START "START"
#define END "END"
#define SHUTDOWN "SHUTDOWN"
#define CONTENT "CONTENT"
#define OKDOWNLOAD "OKDOWNLOAD"
#define SIZEOF_UPLOAD 6
#define SIZEOF_DOWNLOAD 8
#define CMD_MIN_LEN 6
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/stat.h>
#include<fcntl.h>
int main()
{
int fd;
int downloadfd;
char recvbuf[100]="null";
char cmd[100]="null";
struct sockaddr_in server,other;
server.sin_port=htons(12345);
server.sin_addr.s_addr=INADDR_ANY;
server.sin_family=AF_INET;
if(-1==(fd=socket(AF_INET,SOCK_DGRAM,0)))
{
perror("socket error");
exit(1);
}
if(-1==(bind(fd,(struct sockaddr*)&server,sizeof(server))))
{
perror("bind error");
exit(1);
}
socklen_t len=sizeof(other);
while(1)
{
recvfrom(fd,recvbuf,sizeof(recvbuf),0,(struct sockaddr*)&other,&len);
if(!(strcmp(recvbuf,SHUTDOWN)))
{
sendto(fd,SHUTDOWN,sizeof(SHUTDOWN),0,(struct sockaddr*)&other,len);
printf("------> %s\n",recvbuf);
break;
}
char UPLOAD_split[100]="null";
char DOWNLOAD_split[100]="null";
char file[100]="null";
if(strlen(recvbuf)>CMD_MIN_LEN)
{
strncpy(UPLOAD_split,recvbuf,SIZEOF_UPLOAD);
strncpy(DOWNLOAD_split,recvbuf,SIZEOF_DOWNLOAD);
printf("UPLOAD------->%s,DOWNLOAD---------->%s \n",UPLOAD_split,DOWNLOAD_split);
if(!strcmp(UPLOAD_split,UPLOAD))
{
//UPLOAD
strcpy(file,recvbuf+SIZEOF_UPLOAD);
if(strlen(file)>0)
{
char input_1[100]="null";
printf("client will upload a file ,continue? START/NO (default NO) \n");
scanf("%s",&input_1);
if(!strcmp(START,input_1))
{
char readbuf[1000];
int writefd = open(file,O_CREAT|O_RDWR,0666);
sendto(fd,START,sizeof(START),0,(struct sockaddr*)&other,len);
recvfrom(fd,readbuf,sizeof(readbuf),0,(struct sockaddr*)&other,&len);
write(writefd,readbuf,strlen(readbuf));
close(writefd);
}
else
{
sendto(fd,NO,sizeof(NO),0,(struct sockaddr*)&other,len);
}
}
else
{
sendto(fd,"bad file",sizeof("bad file"),0,(struct sockaddr*)&other,len);
}
}
else if(!strcmp(DOWNLOAD_split,DOWNLOAD))
{
//DOWNLOAD
strcpy(file,recvbuf+SIZEOF_DOWNLOAD);
if(strlen(file)>0)
{
if(-1==(downloadfd=open(file,O_RDONLY|O_RDWR,0666)))
{
perror("open error");
sendto(fd,NO,sizeof(NO),0,(struct sockaddr*)&other,len);
}
else
{
printf("find a file \n");
sendto(fd,YES,sizeof(YES),0,(struct sockaddr*)&other,len);
strcpy(cmd,DOWNLOAD);
}
}
}
else
sendto(fd,"return\n",sizeof("return\n"),0,(struct sockaddr*)&other,len);
}
else if(!strcmp(START,recvbuf)&&!strcmp(cmd,DOWNLOAD))
{
char readbuf[1000];
read(downloadfd,readbuf,sizeof(readbuf));
sendto(fd,readbuf,strlen(readbuf),0,(struct sockaddr*)&other,len);
printf("send to client succeed->%s \n",readbuf);
bzero(readbuf,sizeof(readbuf));
}
else
{
sendto(fd,recvbuf,sizeof(recvbuf),0,(struct sockaddr*)&other,len);
printf("->%s \n",recvbuf);
bzero(cmd,sizeof(cmd));
}
bzero(recvbuf,sizeof(recvbuf));
}
close(fd);
return 0;
}