温馨提示×

c语言如何实现websocket通信

小樊
105
2024-08-23 04:21:31
栏目: 编程语言

要实现WebSocket通信,可以使用C语言中的第三方库如libwebsockets或者libwebsocket等。以下是使用libwebsockets库实现WebSocket通信的简单示例:

#include <libwebsockets.h>

static int callback_echo(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len)
{
    switch (reason) {
        case LWS_CALLBACK_ESTABLISHED:
            printf("Connection established\n");
            break;
        case LWS_CALLBACK_RECEIVE:
            printf("Received data: %s\n", (char *)in);
            // Echo back the received data
            lws_write(wsi, in, len, LWS_WRITE_TEXT);
            break;
        default:
            break;
    }

    return 0;
}

int main()
{
    struct lws_context *context;
    struct lws_context_creation_info info;
    struct lws_protocols protocols[] = {
        {
            "echo-protocol",
            callback_echo,
            0,
        },
        {NULL, NULL, 0}
    };

    memset(&info, 0, sizeof(info));
    info.port = 8888;
    info.protocols = protocols;

    context = lws_create_context(&info);

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

    lws_context_destroy(context);

    return 0;
}

这个示例创建了一个简单的WebSocket服务器,监听在端口8888上,当有客户端连接时,在回调函数中处理收到的数据并原样返回。您可以根据实际需求修改回调函数来处理不同的逻辑。

0