aboutsummaryrefslogtreecommitdiff
path: root/connection.c
blob: d12ab8602e6450b2a92cb934654a8250a3d560ad (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
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>

#include "connection.h"
#include "constant.h"

#define READ_BUFFER_SIZE 1024

struct connection *connectionNew(struct tsocket *sock)
{
    struct connection *conn = malloc(sizeof(*conn));
    conn->sock = sock;

    return conn;
}

void connectionDel(struct connection *conn)
{
    tsocketDelete(conn->sock);
    free(conn);
}

int echo(struct connection *conn)
{
    char buf[READ_BUFFER_SIZE];
    ssize_t n_read_bytes;

    struct tsocket *sock = (struct tsocket *)conn->sock;

    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);
            return ERROR;
        } else if (n_read_bytes == -1) {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
                break;
        }
    }

    return OK;
}

struct event *connectionNewEvent(struct connection *conn)
{
    return eventNew(conn, conn->sock->fd, echo, connectionDel);
}