#include #include #include #include #include #include #include #include #include void * next_customer(int new_socket) { char *hello = "Hello from server"; char buffer[1024] = {0}; int valread = read(new_socket, buffer, 1024); printf("%s %d\n", buffer, valread); send(new_socket, hello, strlen(hello), 0); printf("Hello message sent\n"); return NULL; } void serve(int server_fd) { struct sockaddr_in address; int addrlen = sizeof(address); warn("waiting for connections on %d", server_fd); for(int new_socket = 0 ; 1 ; new_socket=accept(server_fd, (struct sockaddr*) &address, (socklen_t*) &addrlen)) { warn("next: %d", new_socket); // next_customer(new_socket); pthread_t thread_id; pthread_create(&thread_id, NULL, next_customer, new_socket); pthread_join(thread_id, NULL); } } #define PORT 8080 int main(int argc, char const *argv[]) { int server_fd; int opt = 1; struct sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); 0 == (server_fd = socket(AF_INET, SOCK_STREAM, 0)) ? err(EXIT_FAILURE, NULL) : setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)) ? err(EXIT_FAILURE, "setsockopt failed on socket with fileno %d", server_fd) : bind(server_fd, (struct sockaddr*) &address, sizeof(address)) ? err(EXIT_FAILURE, NULL) : listen(server_fd, 3) ? err(EXIT_FAILURE, NULL) : serve(server_fd); return 0; } // vim: shiftwidth=2 tabstop=2 number