How do I send async data via libwebsocket?

前端 未结 1 1199
执笔经年
执笔经年 2021-02-04 11:03

I am using warmcat\'s libwebsocket C library for a small websocket server. I have the examples up and working and can send data in response to receiving data from the websocket

1条回答
  •  孤城傲影
    2021-02-04 11:30

    I haven't found a super clean way of doing that. What I would suggest is to register a callback on the event that server can write to the client and then check if there's asynchronous work to send there. the LWS_CALLBACK_SERVER_WRITEABLE event is just that, and if you call libwebsocket_callback_on_writable(context, wsi); from within your callback it'll be periodically called.

    So, something like this:

    static int callback_myprotocol(struct libwebsocket_context *context,
                                   struct libwebsocket *wsi,
                                   enum libwebsocket_callback_reasons reason,
                                   void *user, void *in, size_t len)
    {
        SendState *ss = (SendState*)user;
    
        switch (reason) {
        case LWS_CALLBACK_ESTABLISHED: 
            printf("connection established\n");
            // get the ball rolling
            libwebsocket_callback_on_writable(context, wsi);
            break;
    
        case LWS_CALLBACK_SERVER_WRITEABLE: {
            if (!work_to_be_done) {
                // schedule ourselves to run next tick anyway
                libwebsocket_callback_on_writable(context, wsi);
                return 0;
            }
            // send our asynchronous message
            libwebsocket_write(wsi, buf, size, flag);
            // and schedule ourselves again
            libwebsocket_callback_on_writable(context, wsi);
            break;
        }
        default:
            break;
        }
    
        return 0;
    }
    

    I adapted this from the test-fraggle.c example; the above is roughly what that example does to send messages in smaller chunks.

    0 讨论(0)
提交回复
热议问题