Skip to content

Commit 5354178

Browse files
committed
EventsHandler: Write serialized events directly into the stream
Instead of serializing the events into a JSON `String` and transforming it into an Asio buffer, we can directly write the JSON into an Asio stream using the new `JsonEncoder`.
1 parent 0e21d6b commit 5354178

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

lib/remote/eventshandler.cpp

+9-13
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@
99
#include "base/io-engine.hpp"
1010
#include "base/objectlock.hpp"
1111
#include "base/json.hpp"
12-
#include <boost/asio/buffer.hpp>
1312
#include <boost/asio/write.hpp>
1413
#include <boost/algorithm/string/replace.hpp>
14+
#include <boost/asio/streambuf.hpp>
1515
#include <map>
1616
#include <set>
1717

@@ -110,20 +110,16 @@ bool EventsHandler::HandleRequest(
110110
http::async_write(stream, response, yc);
111111
stream.async_flush(yc);
112112

113-
asio::const_buffer newLine ("\n", 1);
113+
auto adapter(std::make_shared<AsioStreamAdapter<AsioTlsStream>>(stream, yc));
114+
JsonEncoder encoder(adapter);
114115

115116
for (;;) {
116-
auto event (subscriber.GetInbox()->Shift(yc));
117-
118-
if (event) {
119-
String body = JsonEncode(event);
120-
121-
boost::algorithm::replace_all(body, "\n", "");
122-
123-
asio::const_buffer payload (body.CStr(), body.GetLength());
124-
125-
asio::async_write(stream, payload, yc);
126-
asio::async_write(stream, newLine, yc);
117+
if (auto event(subscriber.GetInbox()->Shift(yc)); event) {
118+
encoder.Encode(event);
119+
// Put a newline at the end of each event to render them on a separate line.
120+
adapter->async_put('\n');
121+
// Since shifting the next event may cause the coroutine to yield, we need to flush the
122+
// stream after each event to ensure that the client receives it immediately.
127123
stream.async_flush(yc);
128124
} else if (server.Disconnected()) {
129125
return true;

0 commit comments

Comments
 (0)