libhv
是一个类似于libevent、libev、libuv
的跨平台网络库,提供了更易用的接口和更丰富的协议。
项目开源地址:https://gitee.com/libhv/libhv
Linux系统下编译非常简单,使用Makefile进行编译
./configure
make
make install
编译完成后会生成头文件和库文件
#include "WebSocketServer.h"
#include <thread>
#include <string>
using namespace hv;
int main(int argc, char** argv) {
if (argc < 2) {
printf("Usage: %s port\n", argv[0]);
return -1;
}
int port = atoi(argv[1]);
WebSocketService ws;
ws.onopen = [](const WebSocketChannelPtr& channel, const std::string& url) {
printf("onopen: GET %s\n", url.c_str());
std::string str = "hello";
channel->send(str);
};
ws.onmessage = [=](const WebSocketChannelPtr& channel, const std::string& msg) {
printf("onmessage: %.*s\n", (int)msg.size(), msg.data());
channel->send(msg);
};
ws.onclose = [](const WebSocketChannelPtr& channel) {
printf("onclose\n");
};
websocket_server_t server;
server.port = port;
server.ws = &ws;
websocket_server_run(&server, 0);
// press Enter to stop
while (getchar() != '\n');
websocket_server_stop(&server);
return 0;
}