Skip to content

Commit eaa5f24

Browse files
jacobrosenthaltomusdrw
authored andcommitted
ws: expose broadcaster (paritytech#408)
1 parent 31ec6d6 commit eaa5f24

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

ws/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use jsonrpc_core as core;
2222

2323
pub use self::error::{Error, Result};
2424
pub use self::metadata::{MetaExtractor, NoopExtractor, RequestContext};
25-
pub use self::server::{CloseHandle, Server};
25+
pub use self::server::{Broadcaster, CloseHandle, Server};
2626
pub use self::server_builder::ServerBuilder;
2727
pub use self::server_utils::cors::Origin;
2828
pub use self::server_utils::hosts::{DomainsValidation, Host};

ws/src/server.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,13 @@ impl Server {
3838
&self.addr
3939
}
4040

41+
/// Returns a Broadcaster that can be used to send messages on all connections.
42+
pub fn broadcaster(&self) -> Broadcaster {
43+
Broadcaster {
44+
broadcaster: self.broadcaster.clone(),
45+
}
46+
}
47+
4148
/// Starts a new `WebSocket` server in separate thread.
4249
/// Returns a `Server` handle which closes the server when droped.
4350
pub fn start<M: core::Metadata, S: core::Middleware<M>>(
@@ -160,3 +167,26 @@ impl CloseHandle {
160167
}
161168
}
162169
}
170+
171+
/// A Broadcaster that can be used to send messages on all connections.
172+
#[derive(Clone)]
173+
pub struct Broadcaster {
174+
broadcaster: ws::Sender,
175+
}
176+
177+
impl Broadcaster {
178+
/// Send a message to the endpoints of all connections.
179+
#[inline]
180+
pub fn send<M>(&self, msg: M) -> Result<()>
181+
where
182+
M: Into<ws::Message>,
183+
{
184+
match self.broadcaster.send(msg).map_err(Error::from) {
185+
Err(error) => {
186+
error!("Error while running sending. Details: {:?}", error);
187+
Err(error)
188+
}
189+
Ok(_server) => Ok(()),
190+
}
191+
}
192+
}

0 commit comments

Comments
 (0)