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?