在C语言中搭建WebSocket服务器需要使用一些库来处理WebSocket协议的握手和数据传输。以下是一个简单的示例代码来搭建一个WebSocket服务器:
- 使用libwebsockets库来创建WebSocket服务器。首先需要安装libwebsockets库:
git clone https://github.com/warmcat/libwebsockets.git cd libwebsockets mkdir build cd build cmake .. make sudo make install
- 编写一个简单的WebSocket服务器代码:
#include#include int callback_http(struct lws* wsi, enum lws_callback_reasons reason, void* user, void* in, size_t len) { switch (reason) { case LWS_CALLBACK_HTTP: lws_return_http_status(wsi, HTTP_STATUS_OK, NULL); lws_return_http_body(wsi, "Hello, World!", 13); break; default: break; } return 0; } static struct lws_protocols protocols[] = { { "http-only", callback_http, 0, }, { NULL, NULL, 0, 0 } }; int main() { struct lws_context_creation_info info; memset(&info, 0, sizeof(info)); struct lws_context* context = lws_create_context(&info); struct lws_vhost* vhost = lws_create_vhost(context, &info); struct lws_http_mount mount; memset(&mount, 0, sizeof(mount)); mount.mountpoint = "/"; mount.origin = "./"; mount.protocol = "http-only"; mount.def = "index.html"; lws_vhost_mount_service(vhost, &mount); while (true) { lws_service(context, 0); } lws_context_destroy(context); return 0; }
- 编译并运行代码:
gcc -o websocket_server websocket_server.c -lwebsockets ./websocket_server
这样就可以在本地搭建一个简单的WebSocket服务器了。您可以根据需要添加更多的WebSocket处理逻辑来实现更复杂的功能。