aboutsummaryrefslogtreecommitdiff
path: root/q5/with-threads/server.c
diff options
context:
space:
mode:
Diffstat (limited to 'q5/with-threads/server.c')
-rw-r--r--q5/with-threads/server.c72
1 files changed, 72 insertions, 0 deletions
diff --git a/q5/with-threads/server.c b/q5/with-threads/server.c
new file mode 100644
index 0000000..c2d5c56
--- /dev/null
+++ b/q5/with-threads/server.c
@@ -0,0 +1,72 @@
1#include <stdio.h>
2#include <stdlib.h>
3#include <sys/types.h>
4#include <sys/socket.h>
5#include <netinet/in.h>
6#include <unistd.h>
7#include <string.h>
8#include <arpa/inet.h>
9#include <pthread.h>
10
11void* handle_client(void *);
12
13int client_list[16];
14int client_list_len;
15
16int main(int argc, char *argv[]) {
17 int sockfd;
18
19 pthread_mutex_t list_lock;
20 pthread_mutex_init(&list_lock, NULL);
21
22 struct sockaddr_in servaddr, cli;
23
24 sockfd = socket(AF_INET, SOCK_STREAM, 0);
25 servaddr.sin_family = AF_INET;
26 servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
27
28 int port = atoi(argv[1]);
29 servaddr.sin_port = htons(port);
30
31 bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
32
33 listen(sockfd, 128);
34 printf("Server started at %s...\n", inet_ntoa(servaddr.sin_addr));
35 fflush(stdout);
36
37 while(1) {
38 socklen_t len = sizeof(cli);
39 int connfd = accept(sockfd, (struct sockaddr*)&cli, &len);
40 int i = getpeername(connfd, (struct sockaddr*)&cli, &len);
41
42 client_list[client_list_len] = connfd;
43 client_list_len += 1;
44
45 printf("Clients connected: %d \nDescriptors: ", client_list_len);
46 for(int i = 0; i < client_list_len; i++) {
47 printf("%d ", client_list[i]);
48 }
49 printf("\n");
50 fflush(stdout);
51
52 pthread_t client_thread;
53 pthread_create(&client_thread, NULL, &handle_client, &connfd);
54 }
55 close(sockfd);
56 return 0;
57}
58
59void* handle_client(void* param) {
60 int *connfd = (int *) param;
61 int n;
62 char buf[100];
63 bzero(&buf, 100);
64 while ((n = recv(*connfd, buf, 100, 0)) > 0) {
65 printf("Client message (%d): %s", *connfd, buf);
66 fflush(stdout);
67 send(*connfd, buf, n, 0);
68 bzero(&buf, 100);
69 }
70 close(*connfd);
71 return 0;
72}