要實現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上,當有客戶端連接時,在回調函數中處理收到的數據并原樣返回。您可以根據實際需求修改回調函數來處理不同的邏輯。