我正在尝试调整boost beast的websocket/server/async-ssl/websocket_server_async_ssl.cpp
,以动态刷新index.html
要查看的html表格。我为服务器main.cpp
编写的代码编译并运行在0.0.0.0:8080
上,但是当浏览器查看html文件时,服务器给出一个错误消息accept: uninitialized (SSL routines)
。我用的是boost v1.81.0
。
main.cpp
//------------------------------------------------------------------------------
//
// Example: WebSocket server, asynchronous with SSL/TLS encryption
//
//------------------------------------------------------------------------------
#include <boost/beast/core.hpp>
#include <boost/beast/ssl.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/dispatch.hpp>
#include <boost/asio/strand.hpp>
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include <sstream>
#include <chrono>
#include "utils.hpp"
// Generate the HTML table content with random values
std::string generate_html_table()
{
std::stringstream ss;
// Generate a random number of rows and columns
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 10);
int rows = dis(gen);
int cols = dis(gen);
// Generate a random HTML table with random values
ss << "<table>\n";
for (int i = 0; i < rows; i++) {
ss << "<tr>\n";
for (int j = 0; j < cols; j++) {
std::uniform_int_distribution<> dis(1, 100);
int value = dis(gen);
ss << "<td style=\"background-color:rgb(" << value << "," << value << "," << value << ")\">" << value << "</td>\n";
}
ss << "</tr>\n";
}
ss << "</table>\n";
return ss.str();
}
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
//------------------------------------------------------------------------------
// Report a failure
void fail(beast::error_code ec, char const* what)
{
std::cerr << what << ": " << ec.message() << "\n";
}
// Echoes back all received WebSocket messages
class session : public std::enable_shared_from_this<session>
{
websocket::stream<beast::ssl_stream<beast::tcp_stream>> ws_;
beast::flat_buffer buffer_;
public:
// Take ownership of the socket
explicit session(tcp::socket&& socket, ssl::context& ctx)
: ws_(std::move(socket), ctx)
{
}
// Get on the correct executor
void run()
{
// We need to be executing within a strand to perform async operations
// on the I/O objects in this session. Although not strictly necessary
// for single-threaded contexts, this example code is written to be
// thread-safe by default.
net::dispatch(ws_.get_executor(),
beast::bind_front_handler(
&session::on_run,
shared_from_this()));
}
// Start the asynchronous operation
void on_run()
{
// Set suggested timeout settings for the websocket
ws_.set_option(
websocket::stream_base::timeout::suggested(
beast::role_type::server));
// Set a decorator to change the Server of the handshake
ws_.set_option(websocket::stream_base::decorator(
[](websocket::response_type& res)
{
res.set(http::field::server,
std::string(BOOST_BEAST_VERSION_STRING) +
" websocket-server-async");
}));
// Accept the websocket handshake
ws_.async_accept(
beast::bind_front_handler(
&session::on_accept,
shared_from_this()));
}
void on_accept(beast::error_code ec)
{
if(ec)
return fail(ec, "accept");
// Send the colorful HTML table
send_html_table();
}
void send_html_table()
{
std::string html;
for (int i = 0; i < 10; i++) {
html += generate_html_table(); // Generate the HTML table content
}
// Create the WebSocket message with the HTML content
ws_.text(true);
ws_.async_write(
net::buffer(html),
[self = shared_from_this()](beast::error_code ec, std::size_t bytes_transferred) {
if (ec)
return fail(ec, "write");
// Clear the buffer
self->buffer_.consume(self->buffer_.size());
// Schedule sending the next HTML table after 1 second
self->schedule_next_send();
});
}
void schedule_next_send()
{
// Wait for 1 second before sending the next HTML table
std::this_thread::sleep_for(std::chrono::seconds(1));
// Check if the socket is still open
if (ws_.is_open())
{
// Send the next HTML table
send_html_table();
}
}
};
//------------------------------------------------------------------------------
// Accepts incoming connections and launches the sessions
class listener : public std::enable_shared_from_this<listener>
{
net::io_context& ioc_;
tcp::acceptor acceptor_;
ssl::context& ctx_;
public:
listener(
net::io_context& ioc,
tcp::endpoint endpoint,
ssl::context& ctx)
: ioc_(ioc)
, acceptor_(ioc)
, ctx_(ctx)
{
beast::error_code ec;
// Open the acceptor
acceptor_.open(endpoint.protocol(), ec);
if(ec)
{
fail(ec, "open");
return;
}
// Allow address reuse
acceptor_.set_option(net::socket_base::reuse_address(true), ec);
if(ec)
{
fail(ec, "set_option");
return;
}
// Bind to the server address
acceptor_.bind(endpoint, ec);
if(ec)
{
fail(ec, "bind");
return;
}
// Start listening for connections
acceptor_.listen(
net::socket_base::max_listen_connections, ec);
if(ec)
{
fail(ec, "listen");
return;
}
}
// Start accepting incoming connections
void run()
{
do_accept();
}
private:
void do_accept()
{
acceptor_.async_accept(
net::make_strand(ioc_),
beast::bind_front_handler(
&listener::on_accept,
shared_from_this()));
}
void on_accept(beast::error_code ec, tcp::socket socket)
{
if(ec)
{
fail(ec, "accept");
}
else
{
std::make_shared<session>(std::move(socket), ctx_)->run();
}
// Accept another connection
do_accept();
}
};
//------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
auto const address = net::ip::make_address("0.0.0.0");
auto const port = static_cast<unsigned short>(8080);
auto const threads = std::max<int>(1, 1);
// The io_context is required for all I/O
net::io_context ioc{threads};
// The SSL context is required, and holds certificates
ssl::context ctx{ssl::context::tlsv12};
// Load certificates
auto path = path_to_project().string();
ctx.use_certificate_chain_file(path + "/certificates/server.crt");
ctx.use_private_key_file(path + "/certificates/server.key", ssl::context::pem);
ctx.use_tmp_dh_file(path + "/certificates/dh2048.pem");
// Verify the certificate
ctx.load_verify_file(path + "/certificates/ca.crt");
ctx.set_verify_mode(ssl::verify_peer);
// Create and launch a listening port
std::make_shared<listener>(ioc, tcp::endpoint{address, port}, ctx)->run();
// Run the I/O service on the requested number of threads
std::vector<std::thread> v;
v.reserve(threads - 1);
for(auto i = threads - 1; i > 0; --i)
v.emplace_back(
[&ioc]
{
ioc.run();
});
ioc.run();
return EXIT_SUCCESS;
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Table</title>
<style>
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 5px;
}
</style>
<script>
var socket = new WebSocket("ws://localhost:8080");
socket.onmessage = function(event) {
var tableContainer = document.getElementById("table-container");
tableContainer.innerHTML = event.data;
};
function refreshTable() {
socket.send("refresh"); // Send a message to the server to request a table refresh
}
// Refresh the table every 1 second
setInterval(refreshTable, 1000);
</script>
</head>
<body>
<h1>Dynamic Table</h1>
<div id="table-container"></div>
</body>
</html>
我怀疑这个bug是在listener
类的on_accept()
方法中。不知何故,SSL没有初始化到这一点。
void on_accept(beast::error_code ec, tcp::socket socket)
{
if(ec)
{
fail(ec, "accept");
}
else
{
std::make_shared<session>(std::move(socket), ctx_)->run();
}
// Accept another connection
do_accept();
}
错误发生在fail(ec, "accept")
行中。
我该怎么解决这个问题?
1条答案
按热度按时间2sbarzqh1#
从这条线可以看出
您的代码实际上(部分)基于示例程序的非SSL版本。这导致了不止一件事的缺失:
你自己有意的改变也有一些问题:
send_html_table()
写入局部变量的内容,即Undefined Behaviour,因为在async_write
完成之前,局部变量已经消失。async_write
的完成处理程序中,您盲目地清除了buffer_
,尽管实际上没有读操作使用它schedule_next_send()
做了与它所承诺的相反的事情。它不进行调度,而是阻塞整个世界--这意味着链上的任何东西至少都无法取得进展,然后不管怎样都发送表<random>
不包含在内(也许它在utils.hpp
中缺失)隐藏在这一切之下的是一个问题,即您无法为服务器密钥设置密码回调。这最初在SSL示例中位于
load_server_certificate
内部。我们不能确定哪些选项适合您的证书,因为我们没有相应的文件。我确实认为
set_verify_mode(ssl::verify_peer)
通常与SSL交换中的客户端相关。修复Demo
忽略丢失的位,下面是修复了上述问题并正常工作的代码:
Live On Coliru
编译对Coliru来说太重了(事实上用
-fsanitize=undefined,address
编译在我的电脑上花了8分钟...)。这里有一个本地的demo: