aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: eb9569e3bcb0e1bb2ae274dffafa119447422eb2 (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
#include <Server.h>
#include <launch-socket.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// dont use stdio in these
volatile sig_atomic_t running = 1;
void sig_int_handler(int num)
{
    running = 0;
}

void on_message(struct Server* server, char message[], ssize_t amountRecv, int socketFD)
{
    if (amountRecv > 0) {
        printf("%s\n", message);
        broadcast(server,socketFD,message); //this calls mutex lock and unlock on server->list_lock
    }
}

int main(int argc, char* argv[])
{
    if (argc < 2) {
        fprintf(stderr, "arg1 must be set for port\n");
        exit(-1);
    }
    int port = atoi(argv[1]);
    if (port == 0) {
        fprintf(stderr, "port must not be 0\n");
        exit(-1);
    }

    struct Server server = server_constructor(AF_INET, SOCK_STREAM, 0, INADDR_ANY, port, 10);
    server.on_message = on_message;
    launch_socket(&server);

    struct sigaction act = { 0 };
    act.sa_handler = &sig_int_handler;
    sigaction(SIGINT, &act, NULL);

    while (running) {
        pause();
    }

    int shut_err = server_close_socket(&server);
    printf("shutdown with %d\n", shut_err);

    return 0;
}