0

We are writing a C++ application which uses Websocket. Since it is used in embedded system, we are using lightweight noPoll C library. Everything works fine if you are doing it in a blocking manner:

 ctx = nopoll_ctx_new();
 listener = nopoll_listener_new(ctx, HOST.c_str(), PORT.c_str());

    //pass 'this' pointer to functions so they could access Websocket class members
    nopoll_ctx_set_on_msg(ctx, listener_on_message, this);
    nopoll_ctx_set_on_open(ctx, listener_on_open, this);
    nopoll_ctx_set_on_accept(ctx, listener_on_accept, this);

    //this function blocks the caller. Listens for events
    nopoll_loop_wait(ctx, 1);

And well, this is bad. We have many other peripherals that need to handled at high frequency, and this function blocks everything (500ms).I managed to write a simple websocket handler function which i call in my main while(true) loop:

 void Websocket::handler() {
    noPollConn *conn = nopoll_conn_accept(ctx, listener);
    if (conn) {
        nopoll_conn_complete_handshake(conn);
        //there I store the connected connections
        conns.push_back(conn);
    }
    //CHECK IN EVERY CONNECTION IF THERE ARE ANY MESSAGES
    //...loop through connections
 }

As mentioned this simple handler is called in main while(true) loop and works fine. But the problem is that now I cannot find any way to check whether the connection is closed (user disconnected). Function nopoll_conn_is_ok(noPollConn *conn) always returns true.

The question is if there is at least possible to write some kind of non-blocking websocket handler? Other C/C++ libraries like websocket++ or libwebsocket have the same implementation with blocking manner. Maybe someone have their own implementations?

Cactus'as
  • 70
  • 10
  • Why block? Run the IO reactor on a single thread (a different thread) if you need it to run outside the main thread. Maybe use Pub/Sub or timers to handle events (it should be easy with [facil.io](https://facil.io), I'm biased, but I wrote it for a reason). P.S. consider adding the peripherals as connections to the library. – Myst Aug 30 '19 at 18:39
  • Yeah. Right now we have other thread with only 'nopoll_wait'. But since it is an embedded system with CPU with only 1 core, it is not actually a thread. Linux systen just switches job between threads and it's not the most optimal way. – Cactus'as Aug 31 '19 at 09:02

0 Answers0