-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.c
122 lines (95 loc) · 2.34 KB
/
main.c
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include "die.h"
#include "buf.h"
#include "loop.h"
#include "socket.h"
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
void
tcp_handler(loop_t *loop, int fd, int tag, int type, int flag, void *args)
{
int len;
char request[4096];
char response[] = "HTTP/1.1 200 OK\r\n"
"Server: DemoWebserver\r\n"
"Connection: keep-alive\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 11\r\n\r\n"
"HelloWorld";
len = recv(fd, request, sizeof(request), 0);
if (len <= 0) {
goto err;
}
len = send(fd, response, sizeof(response), 0);
if (len <= 0) {
goto err;
}
return;
err:
loop_del_event(loop, fd, LOOP_READ | LOOP_WRITE);
close(fd);
}
void
tcp_acceptor(loop_t *loop, int fd, int tag, int type, int flag, void *args)
{
int port;
int acceptfd;
socket_addr_t addr;
char addrstr[SOCKET_ADDR_STRLEN];
acceptfd = socket_accept(fd, &addr);
socket_set_nonblock(acceptfd);
socket_addr_str(&addr, addrstr, &port);
printf("accept: %s:%d on fd %d\n", addrstr, port, acceptfd);
loop_set_event(loop, acceptfd, 0, LOOP_READ, 0, tcp_handler, NULL);
}
void
timer_func(loop_t *loop, int id, int tag, int type, int flag, void *args)
{
printf("timer: %d\n", id);
}
int
main(void)
{
int i;
int fd;
int err;
loop_t *loop;
socket_addr_t addr;
signal(SIGPIPE, SIG_IGN);
loop = loop_open(1024, 1024);
die_unless(loop != NULL);
fd = socket_open(AF_INET6, SOCK_STREAM, 0);
die_unless(fd != -1);
err = socket_set_nonblock(fd);
die_unless(err == 0);
err = socket_set_reuseaddr(fd);
die_unless(err == 0);
err = socket_set_reuseport(fd);
die_unless(err == 0);
err = socket_set_tcp_nodelay(fd);
die_unless(err == 0);
err = socket_set_tcp_nopush(fd);
die_unless(err == 0);
err = socket_addr(&addr, "::", 8080);
die_unless(err == 0);
err = socket_bind(fd, &addr);
die_unless(err == 0);
err = socket_listen(fd, 32);
die_unless(err == 0);
err = loop_set_event(loop, fd, 0, LOOP_READ, 0, tcp_acceptor, NULL);
die_unless(err == 0);
for (i = 0; i < 1024; i++) {
err = loop_set_timer(loop, i, 1, 0, 0, i, 0, timer_func, NULL);
die_unless(err == 0);
}
err = loop_start(loop);
die_errno_unless(err == 0);
loop_close(loop);
goto err;
err:
return 0;
}