1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <uv.h>
5
6 #define DEFAULT_PORT 7000
7 #define DEFAULT_BACKLOG 128
8
9 uv_loop_t *loop;
10 struct sockaddr_in addr;
11
12 typedef struct {
13 uv_write_t req;
14 uv_buf_t buf;
15 } write_req_t;
16
free_write_req(uv_write_t * req)17 void free_write_req(uv_write_t *req) {
18 write_req_t *wr = (write_req_t*) req;
19 free(wr->buf.base);
20 free(wr);
21 }
22
alloc_buffer(uv_handle_t * handle,size_t suggested_size,uv_buf_t * buf)23 void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
24 buf->base = (char*) malloc(suggested_size);
25 buf->len = suggested_size;
26 }
27
on_close(uv_handle_t * handle)28 void on_close(uv_handle_t* handle) {
29 free(handle);
30 }
31
echo_write(uv_write_t * req,int status)32 void echo_write(uv_write_t *req, int status) {
33 if (status) {
34 fprintf(stderr, "Write error %s\n", uv_strerror(status));
35 }
36 free_write_req(req);
37 }
38
echo_read(uv_stream_t * client,ssize_t nread,const uv_buf_t * buf)39 void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
40 if (nread > 0) {
41 write_req_t *req = (write_req_t*) malloc(sizeof(write_req_t));
42 req->buf = uv_buf_init(buf->base, nread);
43 uv_write((uv_write_t*) req, client, &req->buf, 1, echo_write);
44 return;
45 }
46 if (nread < 0) {
47 if (nread != UV_EOF)
48 fprintf(stderr, "Read error %s\n", uv_err_name(nread));
49 uv_close((uv_handle_t*) client, on_close);
50 }
51
52 free(buf->base);
53 }
54
on_new_connection(uv_stream_t * server,int status)55 void on_new_connection(uv_stream_t *server, int status) {
56 if (status < 0) {
57 fprintf(stderr, "New connection error %s\n", uv_strerror(status));
58 // error!
59 return;
60 }
61
62 uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
63 uv_tcp_init(loop, client);
64 if (uv_accept(server, (uv_stream_t*) client) == 0) {
65 uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read);
66 }
67 else {
68 uv_close((uv_handle_t*) client, on_close);
69 }
70 }
71
main()72 int main() {
73 loop = uv_default_loop();
74
75 uv_tcp_t server;
76 uv_tcp_init(loop, &server);
77
78 uv_ip4_addr("0.0.0.0", DEFAULT_PORT, &addr);
79
80 uv_tcp_bind(&server, (const struct sockaddr*)&addr, 0);
81 int r = uv_listen((uv_stream_t*) &server, DEFAULT_BACKLOG, on_new_connection);
82 if (r) {
83 fprintf(stderr, "Listen error %s\n", uv_strerror(r));
84 return 1;
85 }
86 return uv_run(loop, UV_RUN_DEFAULT);
87 }
88