c++实现hvlib库websocket服务端和客户端
时间: 2023-07-26 14:07:58 浏览: 184
C++基于Qt实现局域网Socket通信系统源码,有服务端和客户端,服务端默认监听本机IP的6666
下面是使用 hvlib 库实现 WebSocket 服务端和客户端的 C++ 代码示例:
WebSocket 服务端:
```cpp
#include "HttpServer.h"
#include "WebSocket.h"
using namespace hv;
class EchoWebSocketHandler : public WebSocketHandler {
public:
virtual void onOpen(WebSocketChannel* channel) override {
WebSocketHandler::onOpen(channel);
printf("WebSocket onOpen: %s\n", channel->getPeerAddr().c_str());
}
virtual void onClose(WebSocketChannel* channel) override {
WebSocketHandler::onClose(channel);
printf("WebSocket onClose: %s\n", channel->getPeerAddr().c_str());
}
virtual void onMessage(WebSocketChannel* channel, const std::string& payload, bool isBinary) override {
WebSocketHandler::onMessage(channel, payload, isBinary);
printf("WebSocket onMessage: %s, isBinary=%d\n", payload.c_str(), isBinary);
channel->send(payload, isBinary);
}
};
int main() {
HttpServer server;
server.setReusePort(true);
server.get("/hello", [](HttpRequest* req, HttpResponse* resp) {
resp->body = "Hello, world!";
});
server.websocket("/echo", [](WebSocketChannel* channel) {
channel->setHandler(new EchoWebSocketHandler);
});
server.listen("0.0.0.0", 8080);
server.run();
return 0;
}
```
WebSocket 客户端:
```cpp
#include "WebSocketClient.h"
using namespace hv;
class EchoWebSocketClient : public WebSocketClient {
public:
virtual void onOpen() override {
WebSocketClient::onOpen();
printf("WebSocket onOpen\n");
send("Hello, WebSocket!", false);
}
virtual void onClose() override {
WebSocketClient::onClose();
printf("WebSocket onClose\n");
}
virtual void onMessage(const std::string& payload, bool isBinary) override {
WebSocketClient::onMessage(payload, isBinary);
printf("WebSocket onMessage: %s, isBinary=%d\n", payload.c_str(), isBinary);
close();
}
};
int main() {
EventLoop loop;
EchoWebSocketClient client;
client.connect(&loop, "ws://127.0.0.1:8080/echo");
loop.loop();
return 0;
}
```
需要注意的是,在服务端使用 WebSocket 时,需要将连接升级为 WebSocket 连接,可以使用 `HttpServer` 类中的 `websocket` 方法来实现;在客户端使用 WebSocket 时,需要先建立连接,然后才能发送和接收消息。另外,需要注意正确处理 WebSocket 的生命周期事件,如 `onOpen`、`onClose`、`onMessage` 等。
阅读全文