首页 > 解决方案 > Libwesockets:如何从 websocket 正确读取文本(json)数据?

问题描述

我有这样的 websocket 实现,它以前可以工作,但现在不行,因为我升级了库版本。

    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 );
    }

问题是数据最后会带有一些噪音。

如果我从一端发送,{}我会在另一端接收{}/S4T1u3F2O1AA82K7Kg=。因此*in在实际消息字符串之后包含此噪声。我怎样才能正确接收数据?

我尝试了不同的示例,但它们看起来过于复杂。

标签: cwebsocketlibwebsockets

解决方案


我设法将适量的数据复制到字符串中。我的解决方案:

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

推荐阅读