aboutsummaryrefslogtreecommitdiff
path: root/server.c
blob: bc856f92f77081a0399e2f547d994ddba9b42751 (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <strings.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <errno.h>

#include "eventloop.h"
#include "tsocket.h"
#include "util.h"

#define READ_BUFFER_SIZE 1024

void handleEvent(struct tsocket *sock)
{
    char buf[READ_BUFFER_SIZE];
    ssize_t n_read_bytes;

    for (;;) {
        n_read_bytes = read(sock->fd, buf, sizeof(buf));
        if (n_read_bytes > 0) {
            printf("message from conn %d: %s\n", sock->fd, buf);
            write(sock->fd, buf, sizeof(buf));
        } else if (n_read_bytes == 0) {
            printf("conn %d disconnected\n", sock->fd);
            tsocketDelete(sock);
            break;
        } else if (n_read_bytes == -1) {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
                break;
        }
    }
}

int main()
{
    struct tsocket *sock = tsocketNew();
    if (sock == NULL)
        panic("socket creation error");

    if (tsocketBind(sock, "127.0.0.1", 8888) == -1)
        panic("socket bind error");

    if (tsocketListen(sock) == -1)
        panic("socket listen error");

    struct eventLoop *el = eventLoopNew();
    if (el == NULL)
        panic("eventloop creation");

    if (eventLoopAddSocket(el, sock, EPOLLIN) == -1)
        panic("eventloop add fd");

    int nfds;
    struct tsocket *conn_sock;
    for (;;) {
        nfds = eventLoopWait(el, -1);
        if (nfds == -1)
            panic("eventloop wait");

        for (int i = 0; i < nfds; i++) {
            if (eventLoopGetSocket(el, i) == sock) {
                conn_sock = tsocketAccept(sock);
                if (conn_sock == NULL)
                    panic("socket accept error");

                if (setblocking(conn_sock->fd, false) == -1) {
                    tsocketDelete(conn_sock);
                    continue;
                }
                
                if (eventLoopAddSocket(el, conn_sock, EPOLLIN | EPOLLET) == -1)
                    panic("eventloop add fd: conn_sockfd");

                printf("New client fd %d, ip: %s, port: %d\n", 
                        conn_sock->fd, conn_sock->addr, conn_sock->port);
            } else {
                handleEvent(eventLoopGetSocket(el, i));
            }
        }
    }
}