#include #include #include #include #include #define PORT 8081 void send_file(int fd,char* filename) { int fp = open(filename,O_RDONLY); printf("file:%s",filename); if(fp < 0) { printf("file doesn't open\n"); return ; } char buffer[1024]; int bytes_read; while((bytes_read = read(fp,buffer,sizeof(buffer)))>0) { if((send(fd,buffer,bytes_read,0))<0) { perror("send data failed\n"); break; } } close(fp); return; } int main() { int sockfd,new_socket; struct sockaddr_in address; if((sockfd = socket(AF_INET,SOCK_STREAM,0))<0) perror("socket creation failed\n"); address.sin_family = AF_INET; address.sin_port = htons(PORT); address.sin_addr.s_addr = INADDR_ANY; if((bind(sockfd,(struct sockaddr*)&address,sizeof(address)))<0) perror("bind failed\n"); if((listen(sockfd,3))<0) perror("server listening failed\n"); else printf("server listening\n"); int addrlen =sizeof(address); while((new_socket = accept(sockfd, (struct sockaddr *)&address, (socklen_t*)&addrlen))) { printf("connected to client\n"); char s[20]; int read_data; read_data = read(new_socket,s,sizeof(s)-1); s[read_data]='\0'; printf("which file we want to read\n"); send_file(new_socket,s); printf("file sent to client\n"); close(new_socket); } close(sockfd); }