diff options
Diffstat (limited to 'q5/server.c')
-rw-r--r-- | q5/server.c | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/q5/server.c b/q5/server.c new file mode 100644 index 0000000..87870bb --- /dev/null +++ b/q5/server.c | |||
@@ -0,0 +1,86 @@ | |||
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 | |||
11 | void* handle_client(void *); | ||
12 | |||
13 | int client_list[16]; | ||
14 | int client_list_len; | ||
15 | |||
16 | int main(int argc, char *argv[]) { | ||
17 | int sockfd, connfd; | ||
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 | connfd = accept(sockfd, (struct sockaddr *)&cli, &len); | ||
40 | int i = getpeername(connfd, (struct sockaddr*)&cli, &len); | ||
41 | |||
42 | pthread_mutex_lock(&list_lock); | ||
43 | client_list[client_list_len] = connfd; | ||
44 | client_list_len += 1; | ||
45 | pthread_mutex_unlock(&list_lock); | ||
46 | |||
47 | int n; | ||
48 | char buf[100]; | ||
49 | |||
50 | // if((pid=fork())==0){ | ||
51 | // close(sockfd); | ||
52 | // while((n = recv(connfd, buf, 100, 0)) > 0) { | ||
53 | // printf("Client message: %s\n", buf); | ||
54 | // fflush(stdout); | ||
55 | // for (int i = 0; i < client_list_len; i++) { | ||
56 | // int curr_conn = client_list[i]; | ||
57 | // if (i != connfd) { | ||
58 | // send(i, buf, n, 0); | ||
59 | // } | ||
60 | // } | ||
61 | // }; | ||
62 | // exit(0); | ||
63 | // } | ||
64 | |||
65 | pthread_t client_thread; | ||
66 | pthread_create(&client_thread, NULL, &handle_client, &connfd); | ||
67 | } | ||
68 | return 0; | ||
69 | } | ||
70 | |||
71 | void* handle_client(void* param) { | ||
72 | int *connfd = (int *) param; | ||
73 | int n; | ||
74 | char buf[100]; | ||
75 | while ((n = recv(*connfd, buf, 100, 0)) > 0) { | ||
76 | printf("Client message (%d): %s", *connfd, buf); | ||
77 | fflush(stdout); | ||
78 | for (int i = 0; i < client_list_len; i++) { | ||
79 | int curr_conn = *(client_list + i); | ||
80 | if (curr_conn != *connfd) { | ||
81 | send(curr_conn, buf, n, 0); | ||
82 | } | ||
83 | } | ||
84 | } | ||
85 | return 0; | ||
86 | } | ||