cwebsocketlibwebsockets

Libwesockets: how to read text (json) data properly from websocket?


I have such websocket implementation and it worked before but now it doesn't because I upgraded library version.

    int Handle(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) {
        switch( reason ) {
            case LWS_CALLBACK_CLOSED: {
                lwsl_notice("Client Disconnected\n");
                break;
            }
            case LWS_CALLBACK_ESTABLISHED: {
                lwsl_notice("Client Connected\n");
                break;
            }
            case LWS_CALLBACK_RECEIVE: {
                lwsl_notice("Message: %s\n", in);
                break;
            }
            default:
                break;
        }

        return 0;
    }

    static struct lws_protocols protocols[] =
    {
        {
            "server",
            Handle,
            sizeof(struct Session),
            LWS_MESSAGE_CHUNK_SIZE,
        },
        { NULL, NULL, 0, 0 }
    };

    int Start() {
        struct lws_context_creation_info info;
        memset( &info, 0, sizeof(info) );

        info.port = 3018;
        info.protocols = protocols;
        info.gid = -1;
        info.uid = -1;

        struct lws_context *context = lws_create_context( &info );

        while( 1 ) {
            lws_service( context, 1000000 );
        }

        lws_context_destroy( context );
    }

The problem is that data coming with some noise at the end.

If I send from one end {} I receive on another end {}/S4T1u3F2O1AA82K7Kg=. So *in contains this noise after actual message string. How I can properly receive the data?

I tried different examples but they looks overcomplicated.


Solution

  • I was managed to copy right amount of data to the string. My solution:

        char data[len]; 
        memcpy(data, in, len);
        data[len] = '\0';