| 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 stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::netrust-analyzer cargo std https://github.com/rust-lang/rust/library/std net/::SocketAddrrust-analyzer cargo core https://github.com/rust-lang/rust/library/core net/socket_addr/SocketAddr#; |
| 25 | |
| 26 | use futuresrust-analyzer cargo futures 0.3.34 crate/::iorust-analyzer cargo futures-util 0.3.34 io/::{BufReaderrust-analyzer cargo futures-util 0.3.34 io/buf_reader/BufReader#, BufWriterrust-analyzer cargo futures-util 0.3.34 io/buf_writer/BufWriter#}; |
| 27 | use hyperrust-analyzer cargo hyper 1.11.0 crate/::serverrust-analyzer cargo hyper 1.11.0 server/::connrust-analyzer cargo hyper 1.11.0 server/conn/::http1rust-analyzer cargo hyper 1.11.0 server/conn/http1/; |
| 28 | use hyperrust-analyzer cargo hyper 1.11.0 crate/::{bodyrust-analyzer cargo hyper 1.11.0 body/::Bytesrust-analyzer cargo bytes 1.12.1 bytes/Bytes#, servicerust-analyzer cargo hyper 1.11.0 service/::service_fnrust-analyzer cargo hyper 1.11.0 service/util/service_fn()., Requestrust-analyzer cargo http 1.5.0 request/Request#, Responserust-analyzer cargo http 1.5.0 response/Response#}; |
| 29 | use hyper_utilrust-analyzer cargo hyper-util 0.1.20 crate/::rtrust-analyzer cargo hyper-util 0.1.20 rt/::TokioIorust-analyzer cargo hyper-util 0.1.20 rt/tokio/TokioIo#; |
| 30 | use sokettorust-analyzer cargo soketto 0.8.1 crate/::{ |
| 31 | handshakerust-analyzer cargo soketto 0.8.1 handshake/::httprust-analyzer cargo soketto 0.8.1 handshake/http/::{is_upgrade_requestrust-analyzer cargo soketto 0.8.1 handshake/http/is_upgrade_request()., Serverrust-analyzer cargo soketto 0.8.1 handshake/http/Server#}, |
| 32 | BoxedErrorrust-analyzer cargo soketto 0.8.1 BoxedError#, |
| 33 | }; |
| 34 | use tokio_utilrust-analyzer cargo tokio-util 0.7.19 crate/::compatrust-analyzer cargo tokio-util 0.7.19 compat/::TokioAsyncReadCompatExtrust-analyzer cargo tokio-util 0.7.19 compat/TokioAsyncReadCompatExt#; |
| 35 | |
| 36 | type FullBodyrust-analyzer cargo soketto 0.8.1 FullBody# = http_body_utilrust-analyzer cargo http-body-util 0.1.5 crate/::Fullrust-analyzer cargo http-body-util 0.1.5 full/Full#<Bytesrust-analyzer cargo bytes 1.12.1 bytes/Bytes#>; |
| 37 | |
| 38 | /// Start up a hyper server. |
| 39 | #[tokiorust-analyzer cargo tokio 1.53.1 crate/::mainrust-analyzer cargo tokio-macros 2.7.2 main:] |
| 40 | async fn mainrust-analyzer cargo soketto 0.8.1 main().() -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<(), BoxedErrorrust-analyzer cargo soketto 0.8.1 BoxedError#> { |
| 41 | env_loggerrust-analyzer cargo env_logger 0.11.11 crate/::initrust-analyzer cargo env_logger 0.11.11 logger/init().(); |
| 42 | |
| 43 | let addr: SocketAddrrust-analyzer cargo core https://github.com/rust-lang/rust/library/core net/socket_addr/SocketAddr# = ([127, 0, 0, 1], 3000).intorust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/impl#[T][`Into<U>`]into().(); |
| 44 | let listener = tokiorust-analyzer cargo tokio 1.53.1 crate/::netrust-analyzer cargo tokio 1.53.1 net/::TcpListenerrust-analyzer cargo tokio 1.53.1 net/tcp/listener/TcpListener#::bindrust-analyzer cargo tokio 1.53.1 net/tcp/listener/impl#[TcpListener]bind().(addr).rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().; |
| 45 | |
| 46 | logrust-analyzer cargo log 0.4.34 crate/::inforust-analyzer cargo log 0.4.34 macros/info!!( |
| 47 | "Listening on http://{:?} — connect and I'll echo back anything you send!", |
| 48 | listener.local_addrrust-analyzer cargo tokio 1.53.1 net/tcp/listener/impl#[TcpListener]local_addr().().unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().() |
| 49 | ); |
| 50 | |
| 51 | loop { |
| 52 | let stream = match listener.acceptrust-analyzer cargo tokio 1.53.1 net/tcp/listener/impl#[TcpListener]accept().().rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll(). { |
| 53 | Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#((stream, addr)) => { |
| 54 | logrust-analyzer cargo log 0.4.34 crate/::inforust-analyzer cargo log 0.4.34 macros/info!!("Accepting new connection: {addr}"); |
| 55 | stream |
| 56 | } |
| 57 | Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(e) => { |
| 58 | logrust-analyzer cargo log 0.4.34 crate/::errorrust-analyzer cargo log 0.4.34 macros/error!!("Accepting new connection failed: {e}"); |
| 59 | continue; |
| 60 | } |
| 61 | }; |
| 62 | |
| 63 | tokiorust-analyzer cargo tokio 1.53.1 crate/::spawnrust-analyzer cargo tokio 1.53.1 task/spawn/spawn().(async { |
| 64 | let io = TokioIorust-analyzer cargo hyper-util 0.1.20 rt/tokio/TokioIo#::newrust-analyzer cargo hyper-util 0.1.20 rt/tokio/impl#[`TokioIo<T>`]new().(stream); |
| 65 | let conn = http1rust-analyzer cargo hyper 1.11.0 server/conn/http1/::Builderrust-analyzer cargo hyper 1.11.0 server/conn/http1/Builder#::newrust-analyzer cargo hyper 1.11.0 server/conn/http1/impl#[Builder]new().().serve_connectionrust-analyzer cargo hyper 1.11.0 server/conn/http1/impl#[Builder]serve_connection().(io, service_fnrust-analyzer cargo hyper 1.11.0 service/util/service_fn().(handlerrust-analyzer cargo soketto 0.8.1 handler().)); |
| 66 | |
| 67 | // Enable upgrades on the connection for the websocket upgrades to work. |
| 68 | let conn = conn.with_upgradesrust-analyzer cargo hyper 1.11.0 server/conn/http1/impl#[`Connection<I, S>`]with_upgrades().(); |
| 69 | |
| 70 | // Log any errors that might have occurred during the connection. |
| 71 | if let Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(err) = conn.rust-analyzer cargo hyper 1.11.0 server/conn/http1/impl#[`UpgradeableConnection<I, S>`][Future]poll().awaitrust-analyzer cargo hyper 1.11.0 server/conn/http1/impl#[`UpgradeableConnection<I, S>`][Future]poll(). { |
| 72 | logrust-analyzer cargo log 0.4.34 crate/::errorrust-analyzer cargo log 0.4.34 macros/error!!("HTTP connection failed {err}"); |
| 73 | } |
| 74 | }); |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | /// Handle incoming HTTP Requests. |
| 79 | async fn handlerrust-analyzer cargo soketto 0.8.1 handler().(req: Requestrust-analyzer cargo http 1.5.0 request/Request#<hyperrust-analyzer cargo hyper 1.11.0 crate/::bodyrust-analyzer cargo hyper 1.11.0 body/::Incomingrust-analyzer cargo hyper 1.11.0 body/incoming/Incoming#>) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<hyperrust-analyzer cargo hyper 1.11.0 crate/::Responserust-analyzer cargo http 1.5.0 response/Response#<FullBodyrust-analyzer cargo soketto 0.8.1 FullBody#>, BoxedErrorrust-analyzer cargo soketto 0.8.1 BoxedError#> { |
| 80 | if is_upgrade_requestrust-analyzer cargo soketto 0.8.1 handshake/http/is_upgrade_request().(&req) { |
| 81 | // Create a new handshake server. |
| 82 | let mut server = Serverrust-analyzer cargo soketto 0.8.1 handshake/http/Server#::newrust-analyzer cargo soketto 0.8.1 handshake/http/impl#[Server]new().(); |
| 83 | |
| 84 | // Add any extensions that we want to use. |
| 85 | #[cfg(feature = "deflate")] |
| 86 | { |
| 87 | let deflate = sokettorust-analyzer cargo soketto 0.8.1 crate/::extensionrust-analyzer cargo soketto 0.8.1 extension/::deflaterust-analyzer cargo soketto 0.8.1 extension/deflate/::Deflaterust-analyzer cargo soketto 0.8.1 extension/deflate/Deflate#::newrust-analyzer cargo soketto 0.8.1 extension/deflate/impl#[Deflate]new().(sokettorust-analyzer cargo soketto 0.8.1 crate/::Moderust-analyzer cargo soketto 0.8.1 connection/Mode#::Serverrust-analyzer cargo soketto 0.8.1 connection/Mode#Server#); |
| 88 | server.add_extensionrust-analyzer cargo soketto 0.8.1 handshake/http/impl#[Server]add_extension().(Boxrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc boxed/Box#::newrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc boxed/impl#[`Box<T>`]new().(deflate)); |
| 89 | } |
| 90 | |
| 91 | // Attempt the handshake. |
| 92 | match server.receive_requestrust-analyzer cargo soketto 0.8.1 handshake/http/impl#[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 | Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(response) => { |
| 96 | tokiorust-analyzer cargo tokio 1.53.1 crate/::spawnrust-analyzer cargo tokio 1.53.1 task/spawn/spawn().(async move { |
| 97 | if let Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(e) = websocket_echo_messagesrust-analyzer cargo soketto 0.8.1 websocket_echo_messages().(server, req).rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll(). { |
| 98 | logrust-analyzer cargo log 0.4.34 crate/::errorrust-analyzer cargo log 0.4.34 macros/error!!("Error upgrading to websocket connection: {}", e); |
| 99 | } |
| 100 | }); |
| 101 | Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(response.maprust-analyzer cargo http 1.5.0 response/impl#[`Response<T>`]map().(|()| FullBodyrust-analyzer cargo soketto 0.8.1 FullBody#::defaultrust-analyzer cargo http-body-util 0.1.5 full/impl#[`Full<D>`][Default]default().())) |
| 102 | } |
| 103 | // We tried to upgrade and failed early on; tell the client about the failure however we like: |
| 104 | Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(e) => { |
| 105 | logrust-analyzer cargo log 0.4.34 crate/::errorrust-analyzer cargo log 0.4.34 macros/error!!("Could not upgrade connection: {}", e); |
| 106 | Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(Responserust-analyzer cargo http 1.5.0 response/Response#::newrust-analyzer cargo http 1.5.0 response/impl#[`Response<T>`]new().(FullBodyrust-analyzer cargo soketto 0.8.1 FullBody#::fromrust-analyzer cargo http-body-util 0.1.5 full/impl#[`Full<D>`][`From<&'static str>`]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 | Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(Responserust-analyzer cargo http 1.5.0 response/Response#::newrust-analyzer cargo http 1.5.0 response/impl#[`Response<T>`]new().(FullBodyrust-analyzer cargo soketto 0.8.1 FullBody#::fromrust-analyzer cargo http-body-util 0.1.5 full/impl#[`Full<D>`][`From<&'static str>`]from().("Hello HTTP!"))) |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | /// Echo any messages we get from the client back to them |
| 116 | async fn websocket_echo_messagesrust-analyzer cargo soketto 0.8.1 websocket_echo_messages().(server: Serverrust-analyzer cargo soketto 0.8.1 handshake/http/Server#, req: Requestrust-analyzer cargo http 1.5.0 request/Request#<hyperrust-analyzer cargo hyper 1.11.0 crate/::bodyrust-analyzer cargo hyper 1.11.0 body/::Incomingrust-analyzer cargo hyper 1.11.0 body/incoming/Incoming#>) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<(), BoxedErrorrust-analyzer cargo soketto 0.8.1 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 = hyperrust-analyzer cargo hyper 1.11.0 crate/::upgraderust-analyzer cargo hyper 1.11.0 upgrade/::onrust-analyzer cargo hyper 1.11.0 upgrade/on().(req).rust-analyzer cargo hyper 1.11.0 upgrade/impl#[OnUpgrade][Future]poll().awaitrust-analyzer cargo hyper 1.11.0 upgrade/impl#[OnUpgrade][Future]poll().?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().; |
| 124 | let io = TokioIorust-analyzer cargo hyper-util 0.1.20 rt/tokio/TokioIo#::newrust-analyzer cargo hyper-util 0.1.20 rt/tokio/impl#[`TokioIo<T>`]new().(stream); |
| 125 | let stream = BufReaderrust-analyzer cargo futures-util 0.3.34 io/buf_reader/BufReader#::newrust-analyzer cargo futures-util 0.3.34 io/buf_reader/impl#[`BufReader<R>`]new().(BufWriterrust-analyzer cargo futures-util 0.3.34 io/buf_writer/BufWriter#::newrust-analyzer cargo futures-util 0.3.34 io/buf_writer/impl#[`BufWriter<W>`]new().(io.compatrust-analyzer cargo tokio-util 0.7.19 compat/TokioAsyncReadCompatExt#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_builderrust-analyzer cargo soketto 0.8.1 handshake/http/impl#[Server]into_builder().(stream).finishrust-analyzer cargo soketto 0.8.1 connection/impl#[`Builder<T>`]finish().(); |
| 129 | |
| 130 | // Echo any received messages back to the client: |
| 131 | let mut message = Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#::newrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T>`]new().(); |
| 132 | loop { |
| 133 | message.clearrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]clear().(); |
| 134 | match receiver.receive_datarust-analyzer cargo soketto 0.8.1 connection/impl#[`Receiver<T>`]receive_data().(&mut message).rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll(). { |
| 135 | Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(sokettorust-analyzer cargo soketto 0.8.1 crate/::Datarust-analyzer cargo soketto 0.8.1 data/Data#::Binaryrust-analyzer cargo soketto 0.8.1 data/Data#Binary#(n)) => { |
| 136 | assert_eqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/assert_eq!!(n, message.lenrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]len().()); |
| 137 | sender.send_binary_mutrust-analyzer cargo soketto 0.8.1 connection/impl#[`Sender<T>`]send_binary_mut().(&mut message).rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().; |
| 138 | sender.flushrust-analyzer cargo soketto 0.8.1 connection/impl#[`Sender<T>`]flush().().rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch(). |
| 139 | } |
| 140 | Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(sokettorust-analyzer cargo soketto 0.8.1 crate/::Datarust-analyzer cargo soketto 0.8.1 data/Data#::Textrust-analyzer cargo soketto 0.8.1 data/Data#Text#(n)) => { |
| 141 | assert_eqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/assert_eq!!(n, message.lenrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]len().()); |
| 142 | if let Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(txt) = stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::strrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc str/::from_utf8rust-analyzer cargo core https://github.com/rust-lang/rust/library/core str/converts/from_utf8().(&message) { |
| 143 | sender.send_textrust-analyzer cargo soketto 0.8.1 connection/impl#[`Sender<T>`]send_text().(txt).rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().; |
| 144 | sender.flushrust-analyzer cargo soketto 0.8.1 connection/impl#[`Sender<T>`]flush().().rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch(). |
| 145 | } else { |
| 146 | break; |
| 147 | } |
| 148 | } |
| 149 | Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(sokettorust-analyzer cargo soketto 0.8.1 crate/::connectionrust-analyzer cargo soketto 0.8.1 connection/::Errorrust-analyzer cargo soketto 0.8.1 connection/Error#::Closedrust-analyzer cargo soketto 0.8.1 connection/Error#Closed#) => break, |
| 150 | Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(e) => { |
| 151 | eprintlnrust-analyzer cargo std https://github.com/rust-lang/rust/library/std macros/eprintln!!("Websocket connection error: {}", e); |
| 152 | break; |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(()) |
| 158 | } |