#include <iostream>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <boost/beast/websocket.hpp>
namespace asio = boost::asio;
namespace beast = boost::beast;
namespace websocket = beast::websocket;
using tcp = asio::ip::tcp;
class WebSocketSession : public std::enable_shared_from_this<WebSocketSession> {
public:
WebSocketSession(tcp::socket socket)
: ws_(std::move(socket)) {}
void start() {
ws_.async_accept(beast::bind_front_handler(&WebSocketSession::on_accept, shared_from_this()));
}
private:
void on_accept(beast::error_code ec) {
if (ec)
return;
ws_.async_read(buffer_, beast::bind_front_handler(&WebSocketSession::on_read, shared_from_this()));
}
void on_read(beast::error_code ec, std::size_t bytes_transferred) {
if (ec == websocket::error::closed)
return;
if (ec)
return;
// 处理接收到的消息
std::string vbuffer = beast::buffers_to_string(buffer_.data());
std::cout << vbuffer << std::endl;
buffer_.clear();
// 继续等待下一条消息
ws_.async_read(buffer_, beast::bind_front_handler(&WebSocketSession::on_read, shared_from_this()));
}
websocket::stream<beast::tcp_stream> ws_;
beast::flat_buffer buffer_;
};
class WebSocketServer {
public:
WebSocketServer(asio::io_context& ioc, tcp::endpoint endpoint)
: ioc_(ioc), acceptor_(ioc) {
// 创建并打开 acceptor
acceptor_.open(endpoint.protocol());
acceptor_.set_option(asio::socket_base::reuse_address(true));
acceptor_.bind(endpoint);
acceptor_.listen(asio::socket_base::max_listen_connections);
do_accept();
}
private:
void do_accept() {
acceptor_.async_accept(
[this](beast::error_code ec, tcp::socket socket) {
if (!ec) {
// 使用 SSL 上下文创建 WebSocket 会话
std::make_shared<WebSocketSession>(std::move(socket))->start();
}
// 继续等待新的连接
do_accept();
});
}
asio::io_context& ioc_;
tcp::acceptor acceptor_;
};
int main() {
try {
asio::io_context ioc;
tcp::endpoint endpoint(tcp::v4(), 9002);
WebSocketServer server(ioc, endpoint);
ioc.run();
}
catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
标签:std,asio,websocket,阻塞,tcp,beast,_.,boost,acceptor
From: https://www.cnblogs.com/kuangke/p/17963455