websocket/
sender.rs

1//! The default implementation of a WebSocket Sender.
2
3use crate::result::WebSocketResult;
4use crate::stream::sync::AsTcpStream;
5pub use crate::stream::sync::Shutdown;
6use crate::ws;
7use crate::ws::dataframe::DataFrame;
8use crate::ws::sender::Sender as SenderTrait;
9use std::io::Result as IoResult;
10use std::io::Write;
11
12/// A writer that bundles a stream with a serializer to send the messages.
13/// This is used in the client's `.split()` function as the writing component.
14///
15/// It can also be useful to use a websocket connection without a handshake.
16pub struct Writer<W> {
17	/// The stream that websocket messages will be written to
18	pub stream: W,
19	/// The serializer that will be used to serialize the messages
20	pub sender: Sender,
21}
22
23impl<W> Writer<W>
24where
25	W: Write,
26{
27	/// Sends a single data frame to the remote endpoint.
28	pub fn send_dataframe<D>(&mut self, dataframe: &D) -> WebSocketResult<()>
29	where
30		D: DataFrame,
31		W: Write,
32	{
33		self.sender.send_dataframe(&mut self.stream, dataframe)
34	}
35
36	/// Sends a single message to the remote endpoint.
37	pub fn send_message<M>(&mut self, message: &M) -> WebSocketResult<()>
38	where
39		M: ws::Message,
40	{
41		self.sender.send_message(&mut self.stream, message)
42	}
43}
44
45impl<S> Writer<S>
46where
47	S: AsTcpStream + Write,
48{
49	/// Closes the sender side of the connection, will cause all pending and future IO to
50	/// return immediately with an appropriate value.
51	pub fn shutdown(&self) -> IoResult<()> {
52		self.stream.as_tcp().shutdown(Shutdown::Write)
53	}
54
55	/// Shuts down both Sender and Receiver, will cause all pending and future IO to
56	/// return immediately with an appropriate value.
57	pub fn shutdown_all(&self) -> IoResult<()> {
58		self.stream.as_tcp().shutdown(Shutdown::Both)
59	}
60}
61
62/// A Sender that wraps a Writer and provides a default implementation using
63/// DataFrames and Messages.
64pub struct Sender {
65	mask: bool,
66}
67
68impl Sender {
69	/// Create a new WebSocketSender using the specified Writer.
70	pub fn new(mask: bool) -> Sender {
71		Sender { mask }
72	}
73}
74
75impl ws::Sender for Sender {
76	fn is_masked(&self) -> bool {
77		self.mask
78	}
79}