rust-libp2p/example/examples/echo-server.rs

134 lines
6.4 KiB
Rust
Raw Normal View History

2017-11-02 11:58:02 +01:00
// Copyright 2017 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
extern crate bytes;
extern crate futures;
extern crate libp2p_secio as secio;
extern crate libp2p_swarm as swarm;
extern crate libp2p_tcp_transport as tcp;
extern crate tokio_core;
extern crate tokio_io;
use futures::future::{Future, IntoFuture, loop_fn, Loop};
2017-11-02 11:58:02 +01:00
use futures::{Stream, Sink};
2017-12-07 12:56:44 +01:00
use swarm::{Transport, SimpleProtocol};
use tcp::TcpConfig;
2017-11-02 11:58:02 +01:00
use tokio_core::reactor::Core;
use tokio_io::codec::length_delimited;
fn main() {
2017-12-07 18:06:38 +01:00
// We start by building the tokio engine that will run all the sockets.
2017-11-02 11:58:02 +01:00
let mut core = Core::new().unwrap();
2017-12-07 18:06:38 +01:00
// Now let's build the transport stack.
// We start by creating a `TcpConfig` that indicates that we want TCP/IP.
let transport = TcpConfig::new(core.handle())
// On top of TCP/IP, we will use either the plaintext protocol or the secio protocol,
// depending on which one the remote supports.
2017-12-04 16:36:58 +01:00
.with_upgrade(swarm::PlainTextConfig)
2017-11-02 11:58:02 +01:00
.or_upgrade({
2017-12-04 15:39:40 +01:00
let private_key = include_bytes!("test-private-key.pk8");
2017-11-02 11:58:02 +01:00
let public_key = include_bytes!("test-public-key.der").to_vec();
2017-12-04 15:50:14 +01:00
secio::SecioConfig {
2017-12-04 15:39:40 +01:00
key: secio::SecioKeyPair::rsa_from_pkcs8(private_key, public_key).unwrap(),
2017-11-02 11:58:02 +01:00
}
2017-12-07 18:06:38 +01:00
})
// On top of plaintext or secio, we use the "echo" protocol, which is a custom protocol
// just for this example.
// For this purpose, we create a `SimpleProtocol` struct.
.with_upgrade(SimpleProtocol::new("/echo/1.0.0", |socket| {
// This closure is called whenever a stream using the "echo" protocol has been
// successfully negotiated. The parameter is the raw socket (implements the AsyncRead
// and AsyncWrite traits), and the closure must return an implementation of
// `IntoFuture` that can yield any type of object.
Ok(length_delimited::Framed::new(socket))
}));
// We now have a `transport` variable that can be used either to dial nodes or listen to
// incoming connections, and that will automatically apply all the selected protocols on top
// of any opened stream.
2017-11-02 11:58:02 +01:00
2017-12-07 18:06:38 +01:00
// We use it to listen on `/ip4/127.0.0.1/tcp/10333`.
let future = transport.listen_on(swarm::Multiaddr::new("/ip4/0.0.0.0/tcp/10333").unwrap())
.unwrap_or_else(|_| panic!("unsupported multiaddr protocol ; should never happen")).0
2017-11-02 11:58:02 +01:00
.filter_map(|(socket, client_addr)| {
let client_addr = client_addr.to_string();
// This closure is called whenever a new connection has been received. The `socket`
// is a `Result<..., IoError>` which contains an error if for example protocol
// negotiation or the secio handshake failed. We handle this situation by printing a
// message on stderr and ignoring the connection.
match socket {
Ok(s) => Some((s, client_addr)),
Err(err) => {
eprintln!("Failed connection attempt from {}\n => Error: {:?}",
client_addr, err);
None
},
}
})
2017-12-07 18:06:38 +01:00
.for_each(|(socket, client_addr)| {
// This closure is called whenever a new connection has been received and successfully
// upgraded to use secio/plaintext and echo.
println!("Successfully negotiated protocol with {}", client_addr);
let client_addr2 = client_addr.clone();
2017-12-07 18:06:38 +01:00
// We loop forever in order to handle all the messages sent by the client.
let client_finished = loop_fn(socket, move |socket| {
let client_addr = client_addr.clone();
2017-11-02 11:58:02 +01:00
socket.into_future()
.map_err(|(err, _)| err)
.and_then(move |(msg, rest)| {
2017-11-02 11:58:02 +01:00
if let Some(msg) = msg {
2017-12-07 18:06:38 +01:00
// One message has been received. We send it back to the client.
println!("Received a message from {}: {:?}\n => Sending back \
identical message to remote", client_addr, msg);
2017-12-07 18:06:38 +01:00
Box::new(rest.send(msg).map(|m| Loop::Continue(m)))
as Box<Future<Item = _, Error = _>>
2017-11-02 11:58:02 +01:00
} else {
2017-12-07 18:06:38 +01:00
// End of stream. Connection closed. Breaking the loop.
println!("Received EOF from {}\n => Dropping connection", client_addr);
2017-12-07 18:06:38 +01:00
Box::new(Ok(Loop::Break(())).into_future())
as Box<Future<Item = _, Error = _>>
2017-11-02 11:58:02 +01:00
}
})
2017-12-07 18:06:38 +01:00
});
// We absorb errors from the `client_finished` future so that an error while processing
// a client (eg. if the client unexpectedly disconnects) doesn't propagate and stop the
// entire server.
2017-12-07 18:06:38 +01:00
client_finished.then(move |res| {
if let Err(err) = res {
println!("Error while processing client {}: {:?}", client_addr2, err);
2017-12-07 18:06:38 +01:00
}
Ok(())
2017-11-02 11:58:02 +01:00
})
});
2017-12-07 18:06:38 +01:00
// `future` is a future that contains all the behaviour that we want, but nothing has actually
// started yet. Because we created the `TcpConfig` with tokio, we need to run the future
// through the tokio core.
2017-11-02 11:58:02 +01:00
core.run(future).unwrap();
}