Debian Codegraph @

examples/hyper_server.rs

raw symbols SCIP
1 // Copyright (c) 2021 Parity Technologies (UK) Ltd.
2 //
3 // Licensed under the Apache License, Version 2.0
4 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
5 // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. All files in the project carrying such notice may not be copied,
7 // modified, or distributed except according to those terms.
8
9 // An example of how to use of Soketto alongside Hyper, so that we can handle
10 // standard HTTP traffic with Hyper, and WebSocket connections with Soketto, on
11 // the same port.
12 //
13 // To try this, start up the example (`cargo run --example hyper_server`) and then
14 // navigate to localhost:3000 and, in the browser JS console, run:
15 //
16 // ```
17 // var socket = new WebSocket("ws://localhost:3000");
18 // socket.onmessage = function(msg) { console.log(msg) };
19 // socket.send("Hello!");
20 // ```
21 //
22 // You'll see any messages you send echoed back.
23
24 use std::net::SocketAddr;
25
26 use futures::io::{BufReader, BufWriter};
27 use hyper::server::conn::http1;
28 use hyper::{body::Bytes, service::service_fn, Request, Response};
29 use hyper_util::rt::TokioIo;
30 use soketto::{
31 handshake::http::{is_upgrade_request, Server},
32 BoxedError,
33 };
34 use tokio_util::compat::TokioAsyncReadCompatExt;
35
36 type FullBody = http_body_util::Full<Bytes>;
37
38 /// Start up a hyper server.
39 #[tokio::main]
40 async fn main() -> Result<(), BoxedError> {
41 env_logger::init();
42
43 let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
44 let listener = tokio::net::TcpListener::bind(addr).await?;
45
46 log::info!(
47 "Listening on http://{:?} — connect and I'll echo back anything you send!",
48 listener.local_addr().unwrap()
49 );
50
51 loop {
52 let stream = match listener.accept().await {
53 Ok((stream, addr)) => {
54 log::info!("Accepting new connection: {addr}");
55 stream
56 }
57 Err(e) => {
58 log::error!("Accepting new connection failed: {e}");
59 continue;
60 }
61 };
62
63 tokio::spawn(async {
64 let io = TokioIo::new(stream);
65 let conn = http1::Builder::new().serve_connection(io, service_fn(handler));
66
67 // Enable upgrades on the connection for the websocket upgrades to work.
68 let conn = conn.with_upgrades();
69
70 // Log any errors that might have occurred during the connection.
71 if let Err(err) = conn.await {
72 log::error!("HTTP connection failed {err}");
73 }
74 });
75 }
76 }
77
78 /// Handle incoming HTTP Requests.
79 async fn handler(req: Request<hyper::body::Incoming>) -> Result<hyper::Response<FullBody>, BoxedError> {
80 if is_upgrade_request(&req) {
81 // Create a new handshake server.
82 let mut server = Server::new();
83
84 // Add any extensions that we want to use.
85 #[cfg(feature = "deflate")]
86 {
87 let deflate = soketto::extension::deflate::Deflate::new(soketto::Mode::Server);
88 server.add_extension(Box::new(deflate));
89 }
90
91 // Attempt the handshake.
92 match server.receive_request(&req) {
93 // The handshake has been successful so far; return the response we're given back
94 // and spawn a task to handle the long-running WebSocket server:
95 Ok(response) => {
96 tokio::spawn(async move {
97 if let Err(e) = websocket_echo_messages(server, req).await {
98 log::error!("Error upgrading to websocket connection: {}", e);
99 }
100 });
101 Ok(response.map(|()| FullBody::default()))
102 }
103 // We tried to upgrade and failed early on; tell the client about the failure however we like:
104 Err(e) => {
105 log::error!("Could not upgrade connection: {}", e);
106 Ok(Response::new(FullBody::from("Something went wrong upgrading!")))
107 }
108 }
109 } else {
110 // The request wasn't an upgrade request; let's treat it as a standard HTTP request:
111 Ok(Response::new(FullBody::from("Hello HTTP!")))
112 }
113 }
114
115 /// Echo any messages we get from the client back to them
116 async fn websocket_echo_messages(server: Server, req: Request<hyper::body::Incoming>) -> Result<(), BoxedError> {
117 // The negotiation to upgrade to a WebSocket connection has been successful so far. Next, we get back the underlying
118 // stream using `hyper::upgrade::on`, and hand this to a Soketto server to use to handle the WebSocket communication
119 // on this socket.
120 //
121 // Note: awaiting this won't succeed until the handshake response has been returned to the client, so this must be
122 // spawned on a separate task so as not to block that response being handed back.
123 let stream = hyper::upgrade::on(req).await?;
124 let io = TokioIo::new(stream);
125 let stream = BufReader::new(BufWriter::new(io.compat()));
126
127 // Get back a reader and writer that we can use to send and receive websocket messages.
128 let (mut sender, mut receiver) = server.into_builder(stream).finish();
129
130 // Echo any received messages back to the client:
131 let mut message = Vec::new();
132 loop {
133 message.clear();
134 match receiver.receive_data(&mut message).await {
135 Ok(soketto::Data::Binary(n)) => {
136 assert_eq!(n, message.len());
137 sender.send_binary_mut(&mut message).await?;
138 sender.flush().await?
139 }
140 Ok(soketto::Data::Text(n)) => {
141 assert_eq!(n, message.len());
142 if let Ok(txt) = std::str::from_utf8(&message) {
143 sender.send_text(txt).await?;
144 sender.flush().await?
145 } else {
146 break;
147 }
148 }
149 Err(soketto::connection::Error::Closed) => break,
150 Err(e) => {
151 eprintln!("Websocket connection error: {}", e);
152 break;
153 }
154 }
155 }
156
157 Ok(())
158 }