-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecho_server.c
More file actions
87 lines (76 loc) · 2.5 KB
/
Copy pathecho_server.c
File metadata and controls
87 lines (76 loc) · 2.5 KB
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 <stdio.h>
#include <stdlib.h>
#include <uv.h>
// ------------------------------------------------------------------------------------------------
typedef struct {
uv_write_t req;
uv_buf_t buf;
} write_req_t;
void cb_alloc_buffer(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf);
void cb_echo_write(uv_write_t* req, int status);
void cb_echo_read(uv_stream_t* client, ssize_t nread, const uv_buf_t* buf);
void cb_on_new_connection(uv_stream_t* server, int status);
void free_write_req(uv_write_t* req);
// ------------------------------------------------------------------------------------------------
int main() {
uv_loop_t* loop = uv_default_loop();
uv_tcp_t server;
uv_tcp_init(loop, &server);
struct sockaddr_in addr;
uv_ip4_addr("0.0.0.0", 12345, &addr);
uv_tcp_bind(&server, (const struct sockaddr*)&addr, 0);
int r = uv_listen((uv_stream_t*)&server, 2, cb_on_new_connection);
if (r) {
fprintf(stderr, "Listen error %s\n", uv_strerror(r));
return 1;
}
return uv_run(loop, UV_RUN_DEFAULT);
}
// ------------------------------------------------------------------------------------------------
// allocate buffer callback
void cb_alloc_buffer(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
buf->base = (char*)malloc(suggested_size);
buf->len = suggested_size;
}
// echo write callback
void cb_echo_write(uv_write_t* req, int status) {
if (status) {
fprintf(stderr, "Write error %s\n", uv_strerror(status));
}
free_write_req(req);
}
// echo read callback
void cb_echo_read(uv_stream_t* client, ssize_t nread, const uv_buf_t* buf) {
if (nread > 0) {
write_req_t* req = (write_req_t*)malloc(sizeof(write_req_t));
req->buf = uv_buf_init(buf->base, nread);
uv_write((uv_write_t*)req, client, &req->buf, 1, cb_echo_write);
return;
}
if (nread < 0) {
if (nread != UV_EOF)
fprintf(stderr, "Read error %s\n", uv_err_name(nread));
uv_close((uv_handle_t*)client, NULL);
}
free(buf->base);
}
void cb_on_new_connection(uv_stream_t* server, int status) {
if (status < 0) {
fprintf(stderr, "New connection error %s\n", uv_strerror(status));
return;
}
uv_loop_t* loop = uv_default_loop();
uv_tcp_t* client = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));
uv_tcp_init(loop, client);
if (uv_accept(server, (uv_stream_t*)client) == 0) {
uv_read_start((uv_stream_t*)client, cb_alloc_buffer, cb_echo_read);
}
else {
uv_close((uv_handle_t*)client, NULL);
}
}
void free_write_req(uv_write_t* req) {
write_req_t* wr = (write_req_t*)req;
free(wr->buf.base);
free(wr);
}