From 49f460ef208e88da3e23b5cadba8a2f952d0763b Mon Sep 17 00:00:00 2001 From: Alex Hultman Date: Thu, 17 Oct 2019 02:09:48 +0200 Subject: [PATCH] Add app.publish --- src/App.h | 7 +++++++ src/WebSocket.h | 9 ++------- src/WebSocketContextData.h | 10 ++++++++++ 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/App.h b/src/App.h index 8f628f8f8..7473d3fec 100644 --- a/src/App.h +++ b/src/App.h @@ -54,6 +54,13 @@ struct TemplatedApp { httpContext->filter(std::move(filterHandler)); } + /* Publishes a message to all websocket contexts */ + void publish(std::string_view topic, std::string_view message, OpCode opCode, bool compress = false) { + for (auto *webSocketContext : webSocketContexts) { + webSocketContext->getExt()->publish(topic, message, opCode, compress); + } + } + ~TemplatedApp() { /* Let's just put everything here */ if (httpContext) { diff --git a/src/WebSocket.h b/src/WebSocket.h index 9fb322c54..eb24526c9 100644 --- a/src/WebSocket.h +++ b/src/WebSocket.h @@ -170,13 +170,8 @@ struct WebSocket : AsyncSocket { WebSocketContextData *webSocketContextData = (WebSocketContextData *) us_socket_context_ext(SSL, (us_socket_context_t *) us_socket_context(SSL, (us_socket_t *) this) ); - - /* We frame the message right here and only pass raw bytes to the pub/subber */ - char *dst = (char *) malloc(protocol::messageFrameSize(message.size())); - size_t dst_length = protocol::formatMessage(dst, message.data(), message.length(), opCode, message.length(), false); - - webSocketContextData->topicTree.publish(topic, std::string_view(dst, dst_length)); - free(dst); + /* Is the same as publishing per websocket context */ + webSocketContextData->publish(topic, message, opCode, compress); } }; diff --git a/src/WebSocketContextData.h b/src/WebSocketContextData.h index 59c31ee22..da4419eeb 100644 --- a/src/WebSocketContextData.h +++ b/src/WebSocketContextData.h @@ -72,6 +72,16 @@ struct WebSocketContextData { topicTree.drain(); }); } + + /* Helper for topictree publish, common path from app and ws */ + void publish(std::string_view topic, std::string_view message, OpCode opCode, bool compress) { + /* We frame the message right here and only pass raw bytes to the pub/subber */ + char *dst = (char *) malloc(protocol::messageFrameSize(message.size())); + size_t dst_length = protocol::formatMessage(dst, message.data(), message.length(), opCode, message.length(), false); + + topicTree.publish(topic, std::string_view(dst, dst_length)); + ::free(dst); + } }; }