2023-07-21 16:17:01 +08:00
|
|
|
|
#ifndef WEBSOCKETSESSION_H
|
|
|
|
|
#define WEBSOCKETSESSION_H
|
|
|
|
|
|
|
|
|
|
#include "BoostLog.h"
|
|
|
|
|
#include <boost/beast.hpp>
|
|
|
|
|
#include <cstdlib>
|
|
|
|
|
#include <memory>
|
|
|
|
|
#include <string>
|
|
|
|
|
#include <vector>
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @brief Represents an active WebSocket connection to the server
|
|
|
|
|
*/
|
|
|
|
|
class WebSocketSession : public std::enable_shared_from_this<WebSocketSession> {
|
|
|
|
|
public:
|
2024-01-24 23:19:53 +08:00
|
|
|
|
WebSocketSession(boost::asio::ip::tcp::socket &&socket);
|
2023-07-21 16:17:01 +08:00
|
|
|
|
|
|
|
|
|
~WebSocketSession();
|
|
|
|
|
|
|
|
|
|
template <class Body, class Allocator>
|
|
|
|
|
void run(boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>> request) {
|
|
|
|
|
using namespace boost::beast::http;
|
|
|
|
|
using namespace boost::beast::websocket;
|
|
|
|
|
// Set suggested timeout settings for the websocket
|
|
|
|
|
m_ws.set_option(stream_base::timeout::suggested(boost::beast::role_type::server));
|
2024-01-24 23:19:53 +08:00
|
|
|
|
m_target = request.target();
|
2023-07-21 16:17:01 +08:00
|
|
|
|
// Set a decorator to change the Server of the handshake
|
|
|
|
|
m_ws.set_option(stream_base::decorator([](response_type &response) {
|
|
|
|
|
response.set(field::server, std::string(BOOST_BEAST_VERSION_STRING) + " websocket-chat-multi");
|
|
|
|
|
}));
|
|
|
|
|
// LOG(info) << request.base().target(); //get path
|
|
|
|
|
// Accept the websocket handshake
|
|
|
|
|
m_ws.async_accept(request, [self{shared_from_this()}](boost::beast::error_code ec) { self->onAccept(ec); });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Send a message
|
|
|
|
|
void send(std::shared_ptr<std::string const> const &ss);
|
|
|
|
|
|
|
|
|
|
protected:
|
|
|
|
|
void onAccept(boost::beast::error_code ec);
|
|
|
|
|
void on_read(boost::beast::error_code ec, std::size_t bytes_transferred);
|
|
|
|
|
void on_write(boost::beast::error_code ec, std::size_t bytes_transferred);
|
|
|
|
|
void onSend(std::shared_ptr<std::string const> const &ss);
|
|
|
|
|
|
|
|
|
|
private:
|
2024-01-24 23:19:53 +08:00
|
|
|
|
std::string m_target;
|
2023-07-21 16:17:01 +08:00
|
|
|
|
boost::beast::flat_buffer m_buffer;
|
|
|
|
|
boost::beast::websocket::stream<boost::beast::tcp_stream> m_ws;
|
|
|
|
|
std::vector<std::shared_ptr<std::string const>> m_queue;
|
2024-01-24 23:19:53 +08:00
|
|
|
|
std::string m_id;
|
2023-07-21 16:17:01 +08:00
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
#endif // WEBSOCKETSESSION_H
|