aboutsummaryrefslogtreecommitdiff
path: root/q5/with-threads/server.c
blob: c2d5c56f3df807c33880a4a641af509fbf9a7369 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <pthread.h>

void* handle_client(void *);

int client_list[16];
int client_list_len;

int main(int argc, char *argv[]) {
    int sockfd;

    pthread_mutex_t list_lock;
    pthread_mutex_init(&list_lock, NULL);

    struct sockaddr_in servaddr, cli; 
  
    sockfd = socket(AF_INET, SOCK_STREAM, 0); 
    servaddr.sin_family = AF_INET; 
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY); 

    int port = atoi(argv[1]);
    servaddr.sin_port = htons(port);
  
    bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
  
    listen(sockfd, 128);
    printf("Server started at %s...\n", inet_ntoa(servaddr.sin_addr));
    fflush(stdout);

    while(1) {
        socklen_t len = sizeof(cli);
        int connfd = accept(sockfd, (struct sockaddr*)&cli, &len);
        int i = getpeername(connfd, (struct sockaddr*)&cli, &len);

        client_list[client_list_len] = connfd;
        client_list_len += 1;

        printf("Clients connected: %d \nDescriptors: ", client_list_len);
        for(int i = 0; i < client_list_len; i++) {
            printf("%d ", client_list[i]);
        }
        printf("\n");
        fflush(stdout);

        pthread_t client_thread;
        pthread_create(&client_thread, NULL, &handle_client, &connfd);
    }
    close(sockfd);
    return 0;
}

void* handle_client(void* param) {
    int *connfd = (int *) param;
    int n;
    char buf[100];
    bzero(&buf, 100);
    while ((n = recv(*connfd, buf, 100, 0)) > 0) {
        printf("Client message (%d): %s", *connfd, buf);
        fflush(stdout);
        send(*connfd, buf, n, 0);
        bzero(&buf, 100);
    }
    close(*connfd);
    return 0;
}