Hwo to build/debug basic TCP server with libuv

172 views
Skip to first unread message

patrick

unread,
Jan 10, 2020, 5:48:27 AM1/10/20
to libuv
Hello,

I am rather new to systems/network programming with C, but I want to get better. So I have some questions. The background of my questions are these:
To send messages in a network, I have a TCP server without libuv using the Socket API:

      m_addr.sin_family = AF_INET;
     m_addr.sin_port = htons(port);
     m_addr.sin_addr.s_addr = htonl(INADDR_ANY);

My questions:
1) By using libuv and an event loop - I would save CPU resources (in general) or just when there is no incoming request?
2) How to best declar the loop memory space (global and malloc from main or do it in main directly?

    uv_loop_t *loop = malloc(sizeof(uv_loop_t));


3) I wanted to build a basic libuv based socket server example. I succeeded with building a libuv loop listening to idle events - when I try to go to a TCP server example, the event loop does not seem to start. This is the code:

int main() {
    // init loop
    printf("init\n");
    uv_loop_t *loop = malloc(sizeof(uv_loop_t));
    uv_loop_init(loop);

    // need handler
    uv_idle_t idhandler;
    uv_idle_init(loop, &idhandler);
    uv_idle_start(&idhandler, wait_for_a_while);

#ifdef SERVERLOOP
   // attach server to loop
    printf("prepare tcp socket\n");
    uv_tcp_t server;
    uv_tcp_init(loop, &server);

    printf("ip setup");
    uv_ip4_addr("0.0.0.0", DEFAULT_PORT, &addr);
    printf("setup port: %d", DEFAULT_PORT);

    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;
    }
#endif

    uv_run(loop, UV_RUN_DEFAULT);

    uv_loop_close(loop);
    free(loop);
    return 0;

}

When I build this example with the SERVERLOOP define, the printf are not shown. I suspect that the server hangs somewhere, but not sure. 
What can I do to learn more on the uv loop if setup would work? Any debugging statements? Maybe using gdb... ?


Thanks for your help!

patrick

unread,
Jan 10, 2020, 5:52:18 AM1/10/20
to libuv
Ok, at least my example seem to work onw.
As usual, when writing things down, ithe problem seem to go away by itself...

Anyway, maybe someone has general comments on working with libuv for building servers.
Reply all
Reply to author
Forward
0 new messages