[英]Boost beast::websocket callback functions
我正在嘗試使用Boost beast :: websocket websocket_client_async.cpp示例,結合websocket_server_async.cpp 。
如上所述, 客戶端示例只是進行連接,向服務器發送一個字符串(簡單地回顯),打印回復,關閉和存在。
我正在嘗試修改客戶端以使會話保持活動狀態,以便我可以重復發送/接收字符串。 因此,雖然示例代碼的on_handshake
函數通過ws_.async_write(...)
立即發送字符串,但我將其分離為自己的write(...)
函數。
這是我修改過的session
類:
using tcp = boost::asio::ip::tcp;
namespace websocket = boost::beast::websocket;
void fail(boost::system::error_code ec, char const* what)
{
std::cerr << what << ": " << ec.message() << "\n";
}
// Sends a WebSocket message and prints the response
class session : public std::enable_shared_from_this<session>
{
tcp::resolver resolver_;
websocket::stream<tcp::socket> ws_;
std::atomic<bool> io_in_progress_;
boost::beast::multi_buffer buffer_;
std::string host_;
public:
// Resolver and socket require an io_context
explicit session(boost::asio::io_context& ioc) : resolver_(ioc), ws_(ioc) {
io_in_progress_ = false;
}
bool io_in_progress() const {
return io_in_progress_;
}
// +---------------------+
// | The "open" sequence |
// +---------------------+
void open(char const* host, char const* port)
{
host_ = host;
// Look up the domain name
resolver_.async_resolve(host, port,
std::bind( &session::on_resolve, shared_from_this(),
std::placeholders::_1, std::placeholders::_2 )
);
}
void on_resolve(boost::system::error_code ec, tcp::resolver::results_type results)
{
if (ec)
return fail(ec, "resolve");
boost::asio::async_connect(
ws_.next_layer(), results.begin(), results.end(),
std::bind( &session::on_connect, shared_from_this(),
std::placeholders::_1 )
);
}
void on_connect(boost::system::error_code ec)
{
if (ec)
return fail(ec, "connect");
ws_.async_handshake(host_, "/",
std::bind( &session::on_handshake, shared_from_this(),
std::placeholders::_1 )
);
}
void on_handshake(boost::system::error_code ec)
{
if (ec)
return fail(ec, "handshake");
else {
std::cout << "Successful handshake with server.\n";
}
}
// +---------------------------+
// | The "write/read" sequence |
// +---------------------------+
void write(const std::string &text)
{
io_in_progress_ = true;
ws_.async_write(boost::asio::buffer(text),
std::bind( &session::on_write, shared_from_this(),
std::placeholders::_1, std::placeholders::_2 )
);
}
void on_write(boost::system::error_code ec, std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
if (ec)
return fail(ec, "write");
ws_.async_read(buffer_,
std::bind( &session::on_read, shared_from_this(),
std::placeholders::_1, std::placeholders::_2 )
);
}
void on_read(boost::system::error_code ec, std::size_t bytes_transferred)
{
io_in_progress_ = false; // end of write/read sequence
boost::ignore_unused(bytes_transferred);
if (ec)
return fail(ec, "read");
std::cout << boost::beast::buffers(buffer_.data()) << std::endl;
}
// +----------------------+
// | The "close" sequence |
// +----------------------+
void close()
{
io_in_progress_ = true;
ws_.async_close(websocket::close_code::normal,
std::bind( &session::on_close, shared_from_this(),
std::placeholders::_1)
);
}
void on_close(boost::system::error_code ec)
{
io_in_progress_ = false; // end of close sequence
if (ec)
return fail(ec, "close");
std::cout << "Socket closed successfully.\n";
}
};
問題是,雖然連接工作正常並且我可以發送一個字符串,但on_read
回調永遠不會被命中(除非我做了下面描述的丑陋的黑客攻擊)。
我的main
看起來像這樣:
void wait_for_io(std::shared_ptr<session> psession, boost::asio::io_context &ioc)
{
// Continually try to run the ioc until the callbacks are finally
// triggered (as indicated by the session::io_in_progress_ flag)
while (psession->io_in_progress()) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
ioc.run();
}
}
int main(int argc, char** argv)
{
// Check command line arguments.
if (argc != 3) {
std::cerr << "usage info goes here...\n";
return EXIT_FAILURE;
}
const char *host = argv[1], *port = argv[2];
boost::asio::io_context ioc;
std::shared_ptr<session> p = std::make_shared<session>(ioc);
p->open(host, port);
ioc.run(); // This works. Connection is established and all callbacks are executed.
p->write("Hello world"); // String is sent & received by server,
// even before calling ioc.run()
// However, session::on_read callback is never
// reached.
ioc.run(); // This seems to be ignored and returns immediately, so
wait_for_io(p, ioc); // <-- so this hack is necessary
p->close(); // session::on_close is never reached
ioc.run(); // Again, this seems to be ignored and returns immediately, so
wait_for_io(p, ioc); // <-- this is necessary
return EXIT_SUCCESS;
}
如果我這樣做:
p->write("Hello world");
while(1) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
我可以確認服務器發送和接收字符串1 ,並且未達到session::on_read
回調。
p->close()
也會發生同樣的事情。
但是,如果我添加我奇怪的wait_for_io()
函數,一切正常。 我很肯定這是一個可怕的黑客,但我無法弄清楚發生了什么。
1注意:我可以確認消息是否到達服務器,因為我修改了服務器示例以將任何接收到的字符串打印到控制台。 這是我制作的唯一修改。 echo-to-client功能未更改。
在第一次調用之后調用io_context::run()
的原因io_context::run()
(如下所示):
boost::asio::io_context ioc;
std::shared_ptr<session> p = std::make_shared<session>(ioc);
p->open(host, port);
ioc.run(); // This works. Connection is established and all callbacks are executed.
是因為必須在io_context::run
任何后續調用之前調用函數io_context::restart()
。
從文檔 :
io_context ::重啟
重新啟動io_context以准備后續的run()調用。
當由於io_context被停止或用完而導致先前調用這些函數時,必須在run(),run_one(),poll()或poll_one()函數的任何第二次或更高版本的調用之前調用此函數。工作。 在調用restart()之后,io_context對象的stopped()函數將返回false。
io_context::run
只會在沒有更多待處理工作時返回。 如果您只是確保對websocket::stream::async_read
處於活動狀態的掛起調用,那么run
將永遠不會返回並且不需要hacks。 此外,您將收到服務器發送的所有消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.