#include #include #include #include #include #include #include #include #include #include #include #include #include const int PORT = 4632; const int number = 5; using namespace std; struct data{ int socket; sockaddr_in server; pthread_t start_thread; }; void* work_to_do(void* info); void error_checking(int i, char* message) { if(i == -1) { cout << message << endl; exit(0); } } int main(int argc, char** argv) { int domain = AF_INET; int type = SOCK_STREAM; int protocol = 0; int sfd = socket(domain, type, protocol); error_checking(sfd, "invalid socket"); int optval = 1; setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval); struct sockaddr_in client_address; client_address.sin_family = AF_INET; client_address.sin_port = htons(PORT); client_address.sin_addr.s_addr = INADDR_ANY; memset (&(client_address.sin_zero), '\0', 8); if(bind(sfd,(struct sockaddr*) &client_address, sizeof (struct sockaddr)) == -1) cout << "Unsuccessful binding\n"; else cout << "Binding\n"; data threads[number]; for(int i = 0; i < number; ++i) { data & information = threads[i]; information.socket = sfd; information.server = client_address; pthread_create(&information.start_thread, NULL, work_to_do, &information); } for(int i = 0; i < number; ++i) pthread_join(threads[i].start_thread, NULL); pthread_exit(NULL); } void*work_to_do(void* info) { data information = *(data*)info; int new_sfd; if(listen(information.socket, 10) == -1) { cout << "listen() error\n"; exit(0); } else cout << "Listening\n"; int sin_size = sizeof(struct sockaddr_in); while((new_sfd = accept(information.socket, (struct sockaddr *)&information.server, (socklen_t *)&sin_size))) { cout << "connection established\n"; //receive the file from client char file[BUFSIZ]; int receive = read(new_sfd, file, BUFSIZ); if(receive == -1) perror("bad reading"); //write to client char buffer[BUFSIZ]; int writting; int read_file_decrypter = open(file, O_RDONLY); if(read_file_decrypter == -1) perror("bad file decrypter"); else cout << "Sending " << file << ".." << endl; while((writting = read(read_file_decrypter,buffer,BUFSIZ)) > 0) write(new_sfd,buffer, writting); if(read_file_decrypter == -1) perror("file not sent"); else cout << "file sent\n"; close(read_file_decrypter); //close(new_sfd); } pthread_exit(NULL); }