在C语言中实现WebSocket,你可以使用libwebsockets库
- 首先,确保你已经安装了libwebsockets库。如果没有,请访问官方网站(https://libwebsockets.org/)获取安装说明。对于大多数Linux发行版,你可以使用包管理器(如apt或yum)安装libwebsockets。例如,在Ubuntu上,运行以下命令:
sudo apt-get install libwebsockets-dev
- 创建一个名为
websocket_example.c
的新C文件,并添加以下代码:
#include#include #include #include static int callback_example(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 message: %.*s\n", (int)len, (char *)in); break; case LWS_CALLBACK_CLOSED: printf("Connection closed\n"); break; default: break; } return 0; } static struct lws_protocols protocols[] = { {"example-protocol", callback_example, 0, 0}, {NULL, NULL, 0, 0} }; int main(void) { struct lws_context_creation_info info; struct lws_context *context; const char *p; int logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE /* for LLL_ verbosity above NOTICE to be built into lws, * lws must have been configured and built with * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE */ /* | LLL_INFO */ /* | LLL_PARSER */ /* | LLL_HEADER */ /* | LLL_EXT */ /* | LLL_CLIENT */ /* | LLL_LATENCY */ /* | LLL_DEBUG */; lws_set_log_level(logs, NULL); memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */ info.port = CONTEXT_PORT_NO_LISTEN; /* we do not run any server */ info.protocols = protocols; /* * since we know this lws context is only ever going to be used with * one client wsis / fds / sockets at a time, let lws know it doesn't * have to use the default allocations for fd tables up to ulimit -n. * It will just allocate for 1 internal and 1 (+ 1 http2 nwsi) that * we will use. */ info.fd_limit_per_thread = 1 + 1 + 1; context = lws_create_context(&info); if (!context) { lwsl_err("lws init failed\n"); return 1; } while (1) { lws_service(context, 50); } lws_context_destroy(context); return 0; }
- 编译并运行示例代码:
gcc websocket_example.c -o websocket_example -lwebsockets ./websocket_example
- 使用WebSocket客户端(如websocat)连接到你的WebSocket服务器,并发送消息。你应该会看到连接建立、接收到的消息和连接关闭的日志。
这只是一个简单的示例,展示了如何使用libwebsockets库在C语言中实现WebSocket。你可以根据需要修改代码以满足你的需求。更多关于libwebsockets库的信息和示例,请参阅官方文档(https://libwebsockets.org/git/libwebsockets/tree/README.md?h=main)。