在C語言中搭建WebSocket服務器需要使用一些庫來處理WebSocket協議的握手和數據傳輸。以下是一個簡單的示例代碼來搭建一個WebSocket服務器:
git clone https://github.com/warmcat/libwebsockets.git
cd libwebsockets
mkdir build
cd build
cmake ..
make
sudo make install
#include <libwebsockets.h>
#include <stdio.h>
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處理邏輯來實現更復雜的功能。