| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- #pragma once
- #include <websocketpp/config/asio.hpp>
- #include <websocketpp/server.hpp>
- #include <functional>
- #include <iostream>
- #include <string>
- #include <unordered_map>
- #include <mutex>
- #include <regex>
- #include <json/json.h>
- #include "Config.h"
- using namespace std;
- class CWebSocketServer
- {
- private:
-
- typedef websocketpp::server<websocketpp::config::asio> server;
- typedef websocketpp::server<websocketpp::config::asio_tls> server_tls;
- typedef websocketpp::lib::shared_ptr<boost::asio::ssl::context> context_ptr;
- public:
- CWebSocketServer();
- ~CWebSocketServer();
- bool init(uint16_t port = 9002);
- bool sendMsg(websocketpp::connection_hdl hdl, string msg);
- void run();
- void close(websocketpp::connection_hdl hdl); // 关闭与指定客户端的连接
- void stop();
- typedef function<void(websocketpp::connection_hdl hdl, string msg)> Callback_RecvMsg;
- typedef function<void(websocketpp::connection_hdl hdl)> Callback_Close;
- void setCallbackRecvMsg(Callback_RecvMsg pRecvFun) { this->pRecvFun = pRecvFun; };
- void setCallbackClose(Callback_Close pCloseFun) { this->pCloseFun = pCloseFun; };
- private:
- template <typename EndpointType>
- void on_message(EndpointType* s, websocketpp::connection_hdl hdl, typename EndpointType::message_ptr msg);
- template <typename EndpointType>
- void on_open(EndpointType* s, websocketpp::connection_hdl hdl) ;
- template <typename EndpointType>
- void on_close(EndpointType* s, websocketpp::connection_hdl hdl);
- template <typename EndpointType>
- void on_fail(EndpointType* s, websocketpp::connection_hdl hdl);
- context_ptr on_tls_init(websocketpp::connection_hdl hdl) {
- std::cout << "on_tls_init called with hdl: " << hdl.lock().get() << std::endl;
- context_ptr ctx = websocketpp::lib::make_shared<boost::asio::ssl::context>(boost::asio::ssl::context::tlsv13_server);
- try {
- ctx->set_options(boost::asio::ssl::context::default_workarounds |
- boost::asio::ssl::context::no_sslv2 |
- boost::asio::ssl::context::no_sslv3 |
- boost::asio::ssl::context::no_tlsv1 |
- boost::asio::ssl::context::single_dh_use);
- ctx->use_certificate_file("server.crt", boost::asio::ssl::context::pem); // "server.crt"
- ctx->use_private_key_file("server.crt", boost::asio::ssl::context::pem); // "server.key"
- }
- catch (std::exception& e) {
- char str[1024];
- snprintf(str, 1024, "[%s :%d][ %s]", __FUNCTION__, __LINE__, e.what());
- std::cout << str << std::endl;
- }
- return ctx;
- }
- private:
- server m_endpoint;
- server_tls m_endpoint_tls;
- uint16_t m_port; // 端口
- Callback_RecvMsg pRecvFun; // 接收消息回调函数
- Callback_Close pCloseFun; // 连接断开回调函数
- };
|