Older/Server/WebRTC/WebSocketSignalSession.h
amass e3580ec8f4
All checks were successful
Deploy / Build (push) Successful in 5m54s
add ws ping/pong.
2025-01-15 15:24:47 +08:00

56 lines
2.0 KiB
C++

#ifndef __WEBSOCKETSIGNALSESSION_H__
#define __WEBSOCKETSIGNALSESSION_H__
#include "BoostLog.h"
#include <boost/beast.hpp>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
class SignalServer;
/**
* @brief Represents an active WebSocket connection to the server
*/
class WebSocketSignalSession : public std::enable_shared_from_this<WebSocketSignalSession> {
public:
WebSocketSignalSession(boost::asio::ip::tcp::socket &&socket, SignalServer &server, const std::string &id);
~WebSocketSignalSession();
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));
m_target = request.target();
// 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(const std::shared_ptr<std::string> &ss);
void send(std::string &&message);
protected:
void onAccept(boost::beast::error_code ec);
void onRead(const boost::beast::error_code &error, std::size_t bytesTransferred);
void on_write(boost::beast::error_code ec, std::size_t bytes_transferred);
private:
boost::beast::websocket::stream<boost::beast::tcp_stream> m_ws;
SignalServer &m_server;
std::string m_id;
std::string m_target;
boost::beast::flat_buffer m_buffer;
std::vector<std::shared_ptr<std::string>> m_queue;
};
#endif // __WEBSOCKETSIGNALSESSION_H__