1//! A "print-each-packet" server with Tokio
2//!
3//! This server will create a TCP listener, accept connections in a loop, and
4//! put down in the stdout everything that's read off of each TCP connection.
5//!
6//! Because the Tokio runtime uses a thread pool, each TCP connection is
7//! processed concurrently with all other TCP connections across multiple
8//! threads.
9//!
10//! To see this server in action, you can run this in one terminal:
11//!
12//! cargo run --example print\_each\_packet
13//!
14//! and in another terminal you can run:
15//!
16//! cargo run --example connect 127.0.0.1:8080
17//!
18//! Each line you type in to the `connect` terminal should be written to terminal!
19//!
20//! Minimal js example:
21//!
22//! ```js
23//! var net = require("net");
24//!
25//! var listenPort = 8080;
26//!
27//! var server = net.createServer(function (socket) {
28//! socket.on("data", function (bytes) {
29//! console.log("bytes", bytes);
30//! });
31//!
32//! socket.on("end", function() {
33//! console.log("Socket received FIN packet and closed connection");
34//! });
35//! socket.on("error", function (error) {
36//! console.log("Socket closed with error", error);
37//! });
38//!
39//! socket.on("close", function (with_error) {
40//! if (with_error) {
41//! console.log("Socket closed with result: Err(SomeError)");
42//! } else {
43//! console.log("Socket closed with result: Ok(())");
44//! }
45//! });
46//!
47//! });
48//!
49//! server.listen(listenPort);
50//!
51//! console.log("Listening on:", listenPort);
52//! ```
53//!
54
55#![warn(rust_2018_idioms)]
56
57use tokio::net::TcpListener;
58use tokio_stream::StreamExt;
59use tokio_util::codec::{BytesCodec, Decoder};
60
61use std::env;
62
63#[tokio::main]
64async fn main() -> Result<(), Box<dyn std::error::Error>> {
65 // Allow passing an address to listen on as the first argument of this
66 // program, but otherwise we'll just set up our TCP listener on
67 // 127.0.0.1:8080 for connections.
68 let addr = env::args()
69 .nth(1)
70 .unwrap_or_else(|| "127.0.0.1:8080".to_string());
71
72 // Next up we create a TCP listener which will listen for incoming
73 // connections. This TCP listener is bound to the address we determined
74 // above and must be associated with an event loop, so we pass in a handle
75 // to our event loop. After the socket's created we inform that we're ready
76 // to go and start accepting connections.
77 let listener = TcpListener::bind(&addr).await?;
78 println!("Listening on: {}", addr);
79
80 loop {
81 // Asynchronously wait for an inbound socket.
82 let (socket, _) = listener.accept().await?;
83
84 // And this is where much of the magic of this server happens. We
85 // crucially want all clients to make progress concurrently, rather than
86 // blocking one on completion of another. To achieve this we use the
87 // `tokio::spawn` function to execute the work in the background.
88 //
89 // Essentially here we're executing a new task to run concurrently,
90 // which will allow all of our clients to be processed concurrently.
91 tokio::spawn(async move {
92 // We're parsing each socket with the `BytesCodec` included in `tokio::codec`.
93 let mut framed = BytesCodec::new().framed(socket);
94
95 // We loop while there are messages coming from the Stream `framed`.
96 // The stream will return None once the client disconnects.
97 while let Some(message) = framed.next().await {
98 match message {
99 Ok(bytes) => println!("bytes: {:?}", bytes),
100 Err(err) => println!("Socket closed with error: {:?}", err),
101 }
102 }
103 println!("Socket received FIN packet and closed connection");
104 });
105 }
106}
107