-
Notifications
You must be signed in to change notification settings - Fork 1
/
08_websocket.rs
153 lines (133 loc) · 4.95 KB
/
08_websocket.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
use std::env;
mod server {
use futures::{Sink, SinkExt, StreamExt};
use messages::prelude::*;
use tokio::net::TcpListener;
use tokio_tungstenite::tungstenite::{Error as WsError, Message};
pub struct WebSocketConnection<T: Sink<Message>> {
response: T,
}
impl<T> WebSocketConnection<T>
where
T: Sink<Message>,
{
pub fn new(response: T) -> Self {
Self { response }
}
}
impl<T> Actor for WebSocketConnection<T> where T: Sink<Message> + Send + Sync + Unpin + 'static {}
#[async_trait]
impl<T> Notifiable<Result<Message, WsError>> for WebSocketConnection<T>
where
T: Sink<Message> + Send + Sync + Unpin + 'static,
{
async fn notify(&mut self, input: Result<Message, WsError>, context: &Context<Self>) {
let msg = match input {
Ok(msg) => msg,
Err(_err) => return,
};
match msg {
Message::Text(input) => {
let _ = self.response.send(Message::Text(input)).await;
}
Message::Binary(input) => {
let _ = self.response.send(Message::Binary(input)).await;
}
Message::Ping(ping) => {
let _ = self.response.send(Message::Pong(ping)).await;
}
Message::Pong(_) => {
// We don't send ping messages, do nothing.
}
Message::Close(_) => {
context.address().stop().await;
}
}
}
}
pub(super) async fn run(addr: String) {
// Create the event loop and TCP listener we'll accept connections on.
let try_socket = TcpListener::bind(&addr).await;
let listener = try_socket.expect("Failed to bind");
println!("Listening on: {}", addr);
while let Ok((stream, _)) = listener.accept().await {
let (ws_sink, ws_stream) = tokio_tungstenite::accept_async(stream)
.await
.expect("Error during the websocket handshake occurred")
.split();
let addr = WebSocketConnection::new(ws_sink).spawn();
addr.spawn_stream_forwarder(ws_stream);
}
}
}
mod client {
//! Client implementation is respectfull borrowed from [`tokio-tungstenite`] [example].
//! It does not use actors, and is put here just so you can play with the server.
//!
//! [`tokio-tungstenite`]: https://github.com/snapview/tokio-tungstenite
//! [example]: https://github.com/snapview/tokio-tungstenite/blob/master/examples/client.rs
use futures::{future, pin_mut, StreamExt};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};
pub(super) async fn run(connect_addr: String) {
if !connect_addr.starts_with("ws://") {
eprintln!("Server URL must start with `ws://`");
return;
}
let (stdin_tx, stdin_rx) = futures::channel::mpsc::unbounded();
tokio::spawn(read_stdin(stdin_tx));
let (ws_stream, _) = connect_async(connect_addr)
.await
.expect("Failed to connect");
println!("WebSocket handshake has been successfully completed");
let (write, read) = ws_stream.split();
let stdin_to_ws = stdin_rx.map(Ok).forward(write);
let ws_to_stdout = {
read.for_each(|message| async {
let data = message.unwrap().into_data();
tokio::io::stdout().write_all(&data).await.unwrap();
})
};
pin_mut!(stdin_to_ws, ws_to_stdout);
future::select(stdin_to_ws, ws_to_stdout).await;
}
// Our helper method which will read data from stdin and send it along the
// sender provided.
async fn read_stdin(tx: futures::channel::mpsc::UnboundedSender<Message>) {
let mut stdin = tokio::io::stdin();
loop {
let mut buf = vec![0; 1024];
let n = match stdin.read(&mut buf).await {
Err(_) | Ok(0) => break,
Ok(n) => n,
};
buf.truncate(n);
tx.unbounded_send(Message::binary(buf)).unwrap();
}
}
}
#[tokio::main]
async fn main() {
let command = match env::args()
.nth(1)
.map(|s| s.to_ascii_lowercase())
.filter(|c| c == "server" || c == "client")
{
Some(command) => command,
None => {
println!(
"Usage: `cargo run --example 08_websocket -- [client|server] <arg>`, \
where `arg` is either server address or bind address."
);
return;
}
};
let arg = env::args()
.nth(2)
.unwrap_or_else(|| "127.0.0.1:8080".to_owned());
match command.as_ref() {
"server" => server::run(arg).await,
"client" => client::run(arg).await,
_ => unreachable!(),
}
}