Migrate libuv server from 0.10 to 1.0 API

This commit is contained in:
Tony Garnock-Jones 2018-05-01 10:10:15 +01:00
parent 208b20c2f7
commit 611acacdb3
1 changed files with 15 additions and 11 deletions

View File

@ -7,12 +7,13 @@
static int connection_count = 0;
static void on_timer(uv_timer_t *timer, int status) {
static void on_timer(uv_timer_t *timer) {
printf("%d connections\n", connection_count);
}
static uv_buf_t alloc_buffer(uv_handle_t *handle, size_t suggested_size) {
return uv_buf_init(calloc(1, suggested_size), suggested_size);
static void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
buf->base = calloc(1, suggested_size);
buf->len = suggested_size;
}
static void on_write_complete(uv_write_t *req, int status) {
@ -21,8 +22,8 @@ static void on_write_complete(uv_write_t *req, int status) {
free(req);
}
static void on_input(uv_stream_t *conn, ssize_t nread, uv_buf_t buf) {
if (nread == -1) {
static void on_input(uv_stream_t *conn, ssize_t nread, uv_buf_t const *buf) {
if (nread < 0) {
/* here we could check uv_last_error(conn->loop).code to see whether it's UV_EOF or not */
/* but we don't care; just close, and be done */
connection_count--;
@ -31,12 +32,15 @@ static void on_input(uv_stream_t *conn, ssize_t nread, uv_buf_t buf) {
uv_stop(conn->loop);
}
uv_close((uv_handle_t *) conn, NULL);
if (buf->base != NULL) {
free(buf->base);
}
} else {
uv_write_t *req = calloc(1, sizeof(uv_write_t));
/* we just echo what came in. */
req->data = buf.base;
buf.len = nread;
uv_write(req, conn, &buf, 1, on_write_complete);
uv_write_t *req = calloc(1, sizeof(uv_write_t));
uv_buf_t outbuf = { .base = buf->base, .len = nread };
req->data = buf->base;
uv_write(req, conn, &outbuf, 1, on_write_complete);
}
}
@ -74,8 +78,8 @@ int main(int argc, char const *argv[]) {
printf("Accepting connections on port %d.\n", PORTNUMBER);
uv_tcp_init(uv, &serversock);
bind_addr = uv_ip4_addr("0.0.0.0", PORTNUMBER);
uv_tcp_bind(&serversock, bind_addr);
uv_ip4_addr("0.0.0.0", PORTNUMBER, &bind_addr);
uv_tcp_bind(&serversock, (struct sockaddr const *) &bind_addr, 0);
uv_listen((uv_stream_t *) &serversock, 4, on_connection);
uv_timer_init(uv, &stats);