From f1bda1ce1a997b22243b6b177723389db41df1c0 Mon Sep 17 00:00:00 2001 From: Michael Hrstka Date: Thu, 24 Feb 2022 08:40:44 +0100 Subject: [PATCH 1/2] added send_binary_blocking function --- include/crow/websocket.h | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/include/crow/websocket.h b/include/crow/websocket.h index 4555b70da..59a969764 100644 --- a/include/crow/websocket.h +++ b/include/crow/websocket.h @@ -22,6 +22,7 @@ namespace crow struct connection { virtual void send_binary(const std::string& msg) = 0; + virtual void send_binary_blocking(const std::string& msg, boost::system::error_code& ec) = 0; virtual void send_text(const std::string& msg) = 0; virtual void send_ping(const std::string& msg) = 0; virtual void send_pong(const std::string& msg) = 0; @@ -157,6 +158,36 @@ namespace crow do_write(); }); } + + /// Send a binary encoded message in blocking mode. + void send_binary_blocking(const std::string& msg, boost::system::error_code& ec) override + { + auto header = build_header(2, msg.size()); + std::vector buffer; + buffer.emplace_back(boost::asio::buffer(header)); + buffer.emplace_back(boost::asio::buffer(msg)); + + boost::asio::io_service service; + boost::asio::deadline_timer deadline_timer(service); + deadline_timer.expires_from_now(boost::posix_time::seconds(3)); + + deadline_timer.async_wait([&](const boost::system::error_code& err) + { + if(!err) + { + ec = boost::system::errc::make_error_code(boost::system::errc::timed_out); + adaptor_.socket().shutdown(boost::asio::ip::tcp::socket::shutdown_send); + } + }); + + dispatch([&, this] + { + boost::asio::write(adaptor_.socket(), buffer, boost::asio::transfer_all(), ec); + deadline_timer.cancel(); + }); + + service.run(); + } /// Send a plaintext message. void send_text(const std::string& msg) override From ac3d62ef0ac0404eed5608ff797bb0e8285bbe9d Mon Sep 17 00:00:00 2001 From: Michael Hrstka C Date: Thu, 24 Feb 2022 12:31:59 +0100 Subject: [PATCH 2/2] use adaptor_.shutdown_write() Co-authored-by: Farook Al-Sammarraie --- include/crow/websocket.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/crow/websocket.h b/include/crow/websocket.h index 59a969764..f11a67924 100644 --- a/include/crow/websocket.h +++ b/include/crow/websocket.h @@ -176,7 +176,7 @@ namespace crow if(!err) { ec = boost::system::errc::make_error_code(boost::system::errc::timed_out); - adaptor_.socket().shutdown(boost::asio::ip::tcp::socket::shutdown_send); + adaptor_.shutdown_write(); } });