Write a simple TCP Server using libuv

libuv handles multiple IO events using event-based asynchronous callbacks

So you can monitor a large number of files (socket and other file types) with a single thread.
This callback-based programming style has poor readability of the code. Here's a review of the process.

  • Three steps to create a TCP server: creating a TCP socket, binding IP&PORT, LISTEN
  • Then run uv_run
  • When a new connection is established, on_new_connection is invoked. If accept succeeds, start reading sockets or handle errors to close resources.
  • After reading the data, echo_read is called, where we call the write data operation.
  • Call the callback function to release the allocated heap memory after the write operation is completed

Shorter version

Accept new sockets / have new data - > Read data (EOF socket closed, this TCP connection ended) - Write data (reply) - > Callback releases memory


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uv.h>

#define DEFAULT_PORT 7000
#define DEFAULT_BACKLOG 128

uv_loop_t* loop;
struct sockaddr_in addr;

typedef struct {
    uv_write_t req;
    uv_buf_t buf;
} write_req_t;

/// Callback function for releasing resources
void free_write_req(uv_write_t* req) {
    write_req_t* wr = (write_req_t*)req;
    free(wr->buf.base);
    free(wr);
}

/// Allocate space to store accepted data
void alloc_buffer(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
    buf->base = (char*)malloc(suggested_size);
    buf->len = suggested_size;
}

/// Functions called after completion of writing
/// Releasing resources
void echo_write(uv_write_t* req, int status) {
    if (status) {
        fprintf(stderr, "Write error %s\n", uv_strerror(status));
    }
    free_write_req(req);
}

/// Put the data read from the socket socket into request(req) and call the callback function after writing (buf - > base nread bytes) to check the status and release the memory occupied by req.
/// It should be noted that req is handled by callback function when read correctly.
/// When EOF / other errors occur, you need to close the socket and release the memory occupied by buf - > base
/// EOF Representation Socket has been turned off
/// Because there is no callback function at this time.
/// Asynchronous callbacks are error prone
void 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, 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);
}

/// Establishment of a new connection
void on_new_connection(uv_stream_t* server, int status) {
    if (status < 0) {
        fprintf(stderr, "New connection error %s\n", uv_strerror(status));
        // error!
        return;
    }

    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, alloc_buffer, echo_read);
    }
    else {
        uv_close((uv_handle_t*)client, NULL);
    }
}

int main() {
    loop = uv_default_loop();

    uv_tcp_t server;
    uv_tcp_init(loop, &server);

    uv_ip4_addr("0.0.0.0", DEFAULT_PORT, &addr);

    uv_tcp_bind(&server, (const struct sockaddr*) & addr, 0);
    int r = uv_listen((uv_stream_t*)&server, DEFAULT_BACKLOG, on_new_connection);
    if (r) {
        fprintf(stderr, "Listen error %s\n", uv_strerror(r));
        return 1;
    }
    return uv_run(loop, UV_RUN_DEFAULT);
}

Tags: C++ socket Programming

Posted on Mon, 07 Oct 2019 23:58:45 -0700 by VinnyWolf