| 1 |
WebSocket 客户端类 |
| 2 |
|
| 3 |
```c++ |
| 4 |
|
| 5 |
class WebSocketClient { |
| 6 |
|
| 7 |
// 打开回调 |
| 8 |
std::function<void()> onopen; |
| 9 |
// 关闭回调 |
| 10 |
std::function<void()> onclose; |
| 11 |
// 消息回调 |
| 12 |
std::function<void(const std::string& msg)> onmessage; |
| 13 |
|
| 14 |
// 打开 |
| 15 |
int open(const char* url, const http_headers& headers = DefaultHeaders); |
| 16 |
|
| 17 |
// 关闭 |
| 18 |
int close(); |
| 19 |
|
| 20 |
// 发送 |
| 21 |
int send(const std::string& msg); |
| 22 |
int send(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY); |
| 23 |
|
| 24 |
// 设置心跳间隔 |
| 25 |
void setPingInterval(int ms); |
| 26 |
|
| 27 |
// 设置WebSocket握手阶段的HTTP请求 |
| 28 |
void setHttpRequest(const HttpRequestPtr& req); |
| 29 |
|
| 30 |
// 获取WebSocket握手阶段的HTTP响应 |
| 31 |
const HttpResponsePtr& getHttpResponse(); |
| 32 |
|
| 33 |
}; |
| 34 |
|
| 35 |
``` |
| 36 |
|
| 37 |
测试代码见 [examples/websocket_client_test.cpp](../../examples/websocket_client_test.cpp) |