### Hyper HTTP Server in Rust Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt A basic HTTP server implementation using the hyper library, demonstrating routing and handling requests. This example requires the 'hyper' and 'futures' crates. It defines a service that responds to GET requests on '/data' and returns a 404 for other paths. ```rust extern crate hyper; extern crate futures; use std::{thread, time}; use futures::future::FutureResult; use hyper::{Get, StatusCode}; use hyper::header::ContentLength; use hyper::server::{Http, Service, Request, Response}; fn heavy_work() -> String { let duration = time::Duration::from_millis(100); thread::sleep(duration); "done".to_string() } #[derive(Clone, Copy)] struct Echo; impl Service for Echo { type Request = Request; type Response = Response; type Error = hyper::Error; type Future = FutureResult; fn call(&self, req: Request) -> Self::Future { futures::future::ok(match (req.method(), req.path()) { (&Get, "/data") => { let b = heavy_work().into_bytes(); Response::new() .with_header(ContentLength(b.len() as u64)) .with_body(b) } _ => Response::new().with_status(StatusCode::NotFound), }) } } fn main() { let addr = "0.0.0.0:3000".parse().unwrap(); let server = Http::new().bind(&addr, || Ok(Echo)).unwrap(); server.run().unwrap(); } ``` -------------------------------- ### Define a Simple Rocket Route Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Shows the basic setup for a Rocket web application route using procedural macros. ```rust #![feature(plugin)] #![plugin(rocket_codegen)] extern crate rocket; #[get("/")] fn blast_off() -> &'static str { "Hello, Rocket!" } fn main() { rocket::ignite().mount("/", routes![blast_off]).launch(); } ``` -------------------------------- ### Event-Driven I/O with mio Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Implements a basic TCP server using mio for non-blocking I/O and event notification. Requires the mio crate. This example listens for incoming connections on a specified port. ```rust extern crate mio; use mio::*; use mio::tcp::TcpListener; use std::net::SocketAddr; use std::env; const SERVER: Token = Token(0); struct TCPServer { address: SocketAddr, } impl TCPServer { fn new(port: u32) -> Self { let address = format!("0.0.0.0:{}", port).parse::().unwrap(); TCPServer { address } } fn run(&mut self) { let server = TcpListener::bind(&self.address).expect("Could not bind to port"); let poll = Poll::new().unwrap(); poll.register(&server, SERVER, Ready::readable(), PollOpt::edge()).unwrap(); let mut events = Events::with_capacity(1024); loop { poll.poll(&mut events, None).unwrap(); for event in events.iter() { match event.token() { SERVER => { let (_stream, remote) = server.accept().unwrap(); println!("Connection from {}", remote); } _ => unreachable!(), } } } } } fn main() { let args: Vec = env::args().collect(); if args.len() != 2 { eprintln!("Please provide only one port number as argument"); std::process::exit(1); } let mut server = TCPServer::new(args[1].parse::().expect("Could not parse as u32")); server.run(); } ``` -------------------------------- ### Generate X.509 Certificates with OpenSSL Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Uses the openssl crate to generate RSA keys and sign self-signed certificates. Requires the openssl library installed on the system. ```rust extern crate openssl; use std::env; use std::fs::File; use std::io::Write; use openssl::x509::{X509, X509Name}; use openssl::nid::Nid; use openssl::pkey::{PKey, Private}; use openssl::rsa::Rsa; use openssl::error::ErrorStack; use openssl::asn1::Asn1Time; use openssl::bn::{BigNum, MsbOption}; use openssl::hash::MessageDigest; fn create_cert() -> Result<(X509, PKey), ErrorStack> { let mut cert_builder = X509::builder()?; cert_builder.set_version(2)?; let serial_number = { let mut serial = BigNum::new()?; serial.rand(160, MsbOption::MAYBE_ZERO, false)?; serial.to_asn1_integer()? }; cert_builder.set_serial_number(&serial_number)?; let mut name = X509Name::builder()?; name.append_entry_by_text("C", "UK")?; name.append_entry_by_text("CN", "Our common name")?; let cert_name = name.build(); cert_builder.set_issuer_name(&cert_name)?; let not_before = Asn1Time::days_from_now(0)?; cert_builder.set_not_before(¬_before)?; let not_after = Asn1Time::days_from_now(365)?; cert_builder.set_not_after(¬_after)?; cert_builder.set_subject_name(&cert_name)?; let private_key = PKey::from_rsa(Rsa::generate(3072)?)?; cert_builder.set_pubkey(&private_key)?; cert_builder.sign(&private_key, MessageDigest::sha512())?; let cert = cert_builder.build(); Ok((cert, private_key)) } fn main() { if let Some(arg) = env::args().nth(1) { let (cert, _key) = create_cert().expect("could not create cert"); let cert_data = cert.to_pem().expect("could not convert cert to pem"); let mut cert_file = File::create(arg).expect("could not create cert file"); cert_file.write_all(&cert_data).expect("failed to write cert"); let subject = cert.subject_name(); let cn = subject.entries_by_nid(Nid::COMMONNAME).next().expect("failed to get subject"); println!("{}", String::from_utf8(cn.data().as_slice().to_vec()).unwrap()); } } ``` -------------------------------- ### Perform HTTP Requests with Reqwest Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Demonstrates sending JSON-serialized POST requests and parsing JSON responses from GET requests using the Reqwest client. ```rust extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate reqwest; #[derive(Debug, Serialize, Deserialize)] struct Post { title: String, body: String, pinned: bool, } fn main() { let url = "http://localhost:8000/posts"; let post = Post { title: "Testing this".to_string(), body: "Try to write something".to_string(), pinned: true }; let client = reqwest::Client::new(); // POST request with JSON body let res = client.post(url) .json(&post) .send() .unwrap(); println!("Got back: {}", res.status()); // GET request with JSON response parsing let mut posts = client.get(url).send().unwrap(); let json: Vec = posts.json().unwrap(); for post in json { println!("{:?}", post); } } ``` -------------------------------- ### HTTP Request Parsing with nom in Rust Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Parses HTTP request lines using the nom parser combinator library. This example demonstrates how to define parsers for HTTP methods, URLs, and versions. Ensure the 'nom' crate is added to your Cargo.toml. ```rust #[macro_use] extern crate nom; use std::str; use nom::{ErrorKind, IResult}; #[derive(Debug)] enum Method { GET, POST } #[derive(Debug)] struct Request { method: Method, url: String, version: String, } named!(parse_method<&[u8], Method>, return_error!(ErrorKind::Custom(128), alt!(map!(tag!("GET"), |_| Method::GET) | map!(tag!("POST"), |_| Method::POST)))); named!(parse_request<&[u8], Request>, ws!(do_parse!( method: parse_method >> url: map_res!(take_until!(" "), str::from_utf8) >> tag!("HTTP/") >> version: map_res!(take_until!("\r"), str::from_utf8) >> (Request { method: method, url: url.into(), version: version.into() }) ))); fn run_parser(input: &str) { match parse_request(input.as_bytes()) { IResult::Done(rest, value) => println!("Rest: {:?} Value: {:?}", rest, value), IResult::Error(err) => println!("{:?}", err), IResult::Incomplete(needed) => println!("{:?}", needed) } } fn main() { let get = "GET /home/ HTTP/1.1\r\n"; run_parser(get); // Parses successfully let post = "POST /update/ HTTP/1.1\r\n"; run_parser(post); // Parses successfully let wrong = "WRONG /wrong/ HTTP/1.1\r\n"; run_parser(wrong); // Returns error } ``` -------------------------------- ### Create HTTPS Server with Tokio Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Sets up an asynchronous HTTPS server using tokio-tls and native-tls. Requires a PKCS12 certificate file. ```rust extern crate futures; extern crate hyper; extern crate native_tls; extern crate tokio_proto; extern crate tokio_service; extern crate tokio_tls; use std::io; use futures::future::{ok, Future}; use hyper::header::ContentLength; use hyper::{Request, Response, StatusCode}; use native_tls::{Pkcs12, TlsAcceptor}; use tokio_proto::TcpServer; use tokio_service::Service; use tokio_tls::proto; use hyper::server::Http; struct SlowMo; impl Service for SlowMo { type Request = Request; type Response = Response; type Error = io::Error; type Future = Box>; fn call(&self, req: Request) -> Self::Future { println!("Request: {:?}", req); let b = "done".to_string().into_bytes(); Box::new(ok(Response::new() .with_status(StatusCode::Ok) .with_header(ContentLength(b.len() as u64)) .with_body(b))) } } fn main() { let raw_cert = include_bytes!("../cert.pfx"); let cert = Pkcs12::from_der(raw_cert, "foobar").unwrap(); let acceptor = TlsAcceptor::builder(cert).unwrap().build().unwrap(); let proto = proto::Server::new(Http::new(), acceptor); let addr = "0.0.0.0:9999".parse().unwrap(); let srv = TcpServer::new(proto, addr); println!("Listening on {}", addr); srv.serve(|| Ok(SlowMo)); } ``` -------------------------------- ### gRPC Server Implementation in Rust Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Implements a gRPC server for a cab location tracking service. Requires the `grpc_example` crate for service definitions and `grpc` and `protobuf` for gRPC functionality. The server listens on port 9001. ```rust extern crate grpc_example; extern crate grpc; extern crate protobuf; use std::thread; use grpc_example::foobar_grpc::* use grpc_example::foobar_* struct FooBarServer; impl FooBarService for FooBarServer { fn record_cab_location(&self, _m: grpc::RequestOptions, req: CabLocationRequest) -> grpc::SingleResponse { let mut r = CabLocationResponse::new(); println!("Recorded cab {} at {}, {}\n", req.get_name(), req.get_location().latitude, req.get_location().longitude); r.set_accepted(true); grpc::SingleResponse::completed(r) } fn get_cabs(&self, _m: grpc::RequestOptions, _req: GetCabRequest) -> grpc::SingleResponse { let mut r = GetCabResponse::new(); let mut location = Location::new(); location.latitude = 40.7128; location.longitude = -74.0060; let mut one = Cab::new(); one.set_name("Limo".to_owned()); one.set_location(location.clone()); let vec = vec![one]; r.set_cabs(::protobuf::RepeatedField::from_vec(vec)); grpc::SingleResponse::completed(r) } } fn main() { let mut server = grpc::ServerBuilder::new_plain(); server.http.set_port(9001); server.add_service(FooBarServiceServer::new_service_def(FooBarServer)); server.http.set_cpu_pool_threads(4); let _server = server.build().expect("Could not start server"); loop { thread::park(); } } ``` -------------------------------- ### Implement a TCP Client Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Connects to a server and uses buffered I/O to read newline-delimited responses from the server. ```rust use std::net::TcpStream; use std::str; use std::io::{self, BufRead, BufReader, Write}; fn main() { let mut stream = TcpStream::connect("127.0.0.1:8888").expect("Could not connect to server"); loop { let mut input = String::new(); let mut buffer: Vec = Vec::new(); io::stdin().read_line(&mut input).expect("Failed to read from stdin"); stream.write(input.as_bytes()).expect("Failed to write to server"); let mut reader = BufReader::new(&stream); reader.read_until(b'\n', &mut buffer).expect("Could not read into buffer"); print!("{}", str::from_utf8(&buffer).expect("Could not write buffer as string")); } } ``` -------------------------------- ### Implement UDP Multicast Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Supports one-to-many communication by joining a multicast group. The behavior changes based on whether command-line arguments are provided. ```rust use std::{env, str}; use std::net::{UdpSocket, Ipv4Addr}; fn main() { let mcast_group: Ipv4Addr = "239.0.0.1".parse().unwrap(); let port: u16 = 6000; let any = "0.0.0.0".parse().unwrap(); let mut buffer = [0u8; 1600]; if env::args().count() > 1 { // Receiver: join multicast group and listen let socket = UdpSocket::bind((any, port)).expect("Could not bind client socket"); socket.join_multicast_v4(&mcast_group, &any).expect("Could not join multicast group"); socket.recv_from(&mut buffer).expect("Failed to write to server"); print!("{}", str::from_utf8(&buffer).expect("Could not write buffer as string")); } else { // Sender: broadcast to multicast group let socket = UdpSocket::bind((any, 0)).expect("Could not bind socket"); socket.send_to("Hello world!".as_bytes(), &(mcast_group, port)).expect("Failed to write data"); } } ``` -------------------------------- ### Async File Download with Tokio-Curl in Rust Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Combines tokio's event loop with curl for asynchronous HTTP downloads with progress tracking. Requires curl, tokio-core, and tokio-curl crates. ```rust extern crate curl; extern crate tokio_core; extern crate tokio_curl; use curl::easy::Easy; use tokio_core::reactor::Core; use tokio_curl::Session; use std::io::Write; use std::fs::File; fn main() { let mut core = Core::new().unwrap(); let session = Session::new(core.handle()); let mut handle = Easy::new(); let mut file = File::create("foo.zip").unwrap(); handle.get(true).unwrap(); handle.url("http://ipv4.download.thinkbroadband.com/5MB.zip").unwrap(); handle.header_function(|header| { print!("{}", std::str::from_utf8(header).unwrap()); true }).unwrap(); handle.write_function(move |data| { file.write_all(data).unwrap(); Ok(data.len()) }).unwrap(); let request = session.perform(handle); let mut response = core.run(request).unwrap(); println!("{:?}", response.response_code()); } ``` -------------------------------- ### Implement a TCP Echo Server Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Uses a thread-per-connection model to echo received data back to clients. Requires binding to a specific address and port. ```rust use std::net::{TcpListener, TcpStream}; use std::thread; use std::io::{Read, Write, Error}; fn handle_client(mut stream: TcpStream) -> Result<(), Error> { println!("Incoming connection from: {}", stream.peer_addr()?); let mut buf = [0; 512]; loop { let bytes_read = stream.read(&mut buf)?; if bytes_read == 0 { return Ok(()) } stream.write(&buf[..bytes_read])?; } } fn main() { let listener = TcpListener::bind("0.0.0.0:8888").expect("Could not bind"); for stream in listener.incoming() { match stream { Err(e) => { eprintln!("failed: {}", e) } Ok(stream) => { thread::spawn(move || { handle_client(stream).unwrap_or_else(|error| eprintln!("{:?}", error)); }); } } } } ``` -------------------------------- ### gRPC Client for Cab Service in Rust Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt A gRPC client that connects to the cab service on localhost:9001. It sends location updates and queries for nearby cabs. Requires `grpc_example` and `grpc` crates. ```rust extern crate grpc_example; extern crate grpc; use grpc_example::foobar_* use grpc_example::foobar_grpc_* fn main() { let client = FooBarServiceClient::new_plain("127.0.0.1", 9001, Default::default()).unwrap(); // Record a cab location let mut req = CabLocationRequest::new(); req.set_name("foo".to_string()); let mut location = Location::new(); location.latitude = 40.730610; location.longitude = -73.935242; req.set_location(location); let resp = client.record_cab_location(grpc::RequestOptions::new(), req); match resp.wait() { Err(e) => panic!("{:?}", e), Ok((_, r, _)) => println!("{:?}", r), } // Query nearby cabs let mut nearby_req = GetCabRequest::new(); let mut location = Location::new(); location.latitude = 40.730610; location.longitude = -73.935242; nearby_req.set_location(location); let nearby_resp = client.get_cabs(grpc::RequestOptions::new(), nearby_req); match nearby_resp.wait() { Err(e) => panic!("{:?}", e), Ok((_, cabs, _)) => println!("{:?}", cabs), } } ``` -------------------------------- ### Thread-Based Concurrency with Channels Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Demonstrates inter-thread communication using Rust's standard library mpsc channels. Suitable for implementing the actor model pattern for parallel computations. ```rust use std::thread; use std::sync::mpsc; fn main() { let rhs = vec![10, 20, 30, 40, 50, 60, 70]; let lhs = vec![1, 2, 3, 4, 5, 6, 7]; let (tx, rx) = mpsc::channel(); assert_eq!(rhs.len(), lhs.len()); for i in 1..rhs.len() { let rhs = rhs.clone(); let lhs = lhs.clone(); let tx = tx.clone(); let handle = thread::spawn(move || { let s = format!("Thread {} added {} and {}, result {}", i, rhs[i], lhs[i], rhs[i] + lhs[i]); tx.clone().send(s).unwrap(); }); let _ = handle.join().unwrap(); } drop(tx); // Close sender to signal completion for result in rx { println!("{}", result); } } ``` -------------------------------- ### JSON/YAML Serialization with Serde Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Serializes and deserializes Rust structs to/from JSON and YAML using Serde. Requires serde, serde_json, and serde_yaml crates, along with serde_derive. ```rust #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; extern crate serde_yaml; #[derive(Serialize, Deserialize, Debug)] struct ServerConfig { workers: u64, ignore: bool, auth_server: Option } fn main() { let config = ServerConfig { workers: 100, ignore: false, auth_server: Some("auth.server.io".to_string()) }; // YAML serialization/deserialization println!("To and from YAML"); let serialized = serde_yaml::to_string(&config).unwrap(); println!("{}", serialized); let deserialized: ServerConfig = serde_yaml::from_str(&serialized).unwrap(); println!("{:?}", deserialized); // JSON serialization/deserialization println!("To and from JSON"); let serialized = serde_json::to_string(&config).unwrap(); println!("{}", serialized); // Output: {"workers":100,"ignore":false,"auth_server":"auth.server.io"} let deserialized: ServerConfig = serde_json::from_str(&serialized).unwrap(); println!("{:?}", deserialized); } ``` -------------------------------- ### Implement a UDP Echo Server Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Handles connectionless datagrams by cloning the socket for concurrent processing in separate threads. ```rust use std::thread; use std::net::UdpSocket; fn main() { let socket = UdpSocket::bind("0.0.0.0:8888").expect("Could not bind socket"); loop { let mut buf = [0u8; 1500]; let sock = socket.try_clone().expect("Failed to clone socket"); match socket.recv_from(&mut buf) { Ok((_, src)) => { thread::spawn(move || { println!("Handling connection from {}", src); sock.send_to(&buf, &src).expect("Failed to send a response"); }); }, Err(e) => { eprintln!("couldn't recieve a datagram: {}", e); } } } } ``` -------------------------------- ### Handle Asynchronous Tasks with Futures Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Illustrates non-blocking computation using boxed futures, impl trait, and thread pools for CPU-bound tasks. ```rust #![feature(conservative_impl_trait)] extern crate futures; extern crate futures_cpupool; use std::io; use futures::Future; use futures_cpupool::CpuPool; fn check_prime_boxed(n: u64) -> Box> { for i in 2..n { if n % i == 0 { return Box::new(futures::future::ok(false)); } } Box::new(futures::future::ok(true)) } fn check_prime_impl_trait(n: u64) -> impl Future { for i in 2..n { if n % i == 0 { return futures::future::ok(false); } } futures::future::ok(true) } fn check_prime(n: u64) -> bool { for i in 2..n { if n % i == 0 { return false } } true } fn main() { let input: u64 = 58466453; // Using boxed futures let res_one = check_prime_boxed(input); let res_two = check_prime_impl_trait(input); println!("Results are {} and {}", res_one.wait().unwrap(), res_two.wait().unwrap()); // Using thread pool for CPU-bound work let thread_pool = CpuPool::new(4); let res_three = thread_pool.spawn_fn(move || { let temp = check_prime(input); let result: Result = Ok(temp); result }); println!("Result from the last call: {}", res_three.wait().unwrap()); } ``` -------------------------------- ### Implement TLS Client with rustls Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Establishes a secure HTTPS connection using rustls and webpki. This implementation does not rely on OpenSSL. ```rust use std::sync::Arc; use std::net::TcpStream; use std::io::{Read, Write}; extern crate rustls; extern crate webpki; extern crate webpki_roots; fn main() { let mut tls = rustls::ClientConfig::new(); tls.root_store.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS); let name = webpki::DNSNameRef::try_from_ascii_str("my.domain.io") .expect("Could not resolve name"); let mut sess = rustls::ClientSession::new(&Arc::new(tls), name); let mut conn = TcpStream::connect("my.domain.io:8000").unwrap(); let mut stream = rustls::Stream::new(&mut sess, &mut conn); stream.write(concat!( "GET / HTTP/1.1\r\n", "Connection: close\r\n", "\r\n" ).as_bytes()).expect("Could not write request"); let mut plaintext = Vec::new(); stream.read_to_end(&mut plaintext).expect("Could not read"); println!("{}", String::from_utf8(plaintext).expect("Could not print output")); } ``` -------------------------------- ### Implement a REST API with Rocket and Diesel Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Provides a full CRUD implementation for a REST API using Rocket and Diesel ORM, including JSON request/response handling. ```rust #![feature(decl_macro)] #[macro_use] extern crate diesel; #[macro_use] extern crate rocket; extern crate rocket_contrib; #[macro_use] extern crate serde_derive; use rocket_contrib::json::Json; use rocket::response::status::{Created, NoContent}; #[derive(Queryable, Serialize, Deserialize)] pub struct Post { pub id: i32, pub title: String, pub body: String, pub pinned: bool, } #[derive(Insertable, Deserialize, AsChangeset)] #[table_name="posts"] pub struct PostData { pub title: String, pub body: String, pub pinned: bool, } #[get("/posts", format = "application/json")] fn posts_get(db: DB) -> Result>, ApiError> { let posts = get_posts(&db)?; Ok(Json(posts)) } #[get("/posts/", format = "application/json")] fn post_get(db: DB, id: i32) -> Result, ApiError> { let post = get_post(&db, id)?; Ok(Json(post)) } #[post("/posts", format = "json", data = "")] fn post_create(db: DB, post: PostData) -> Result, ApiError> { let post = create_post(&db, post); let url = format!("/post/{}", post); Ok(Created(url, Some("Done".to_string()))) } #[patch("/posts/", format = "application/json", data = "")] fn post_edit(db: DB, id: i32, post: PostData) -> Result, ApiError> { let post = update_post(&db, id, post); Ok(Json(post)) } #[delete("/posts/")] fn post_delete(db: DB, id: i32) -> Result { delete_post(&db, id)?; Ok(NoContent) } fn main() { rocket::ignite() .mount("/", routes![post_create, posts_get, post_delete, post_edit, post_get]) .launch(); } ``` -------------------------------- ### DNS Resolution with trust-dns Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Performs IP and NS record lookups using both synchronous and system resolvers. Ensure the trust_dns_resolver and trust_dns crates are added as dependencies. ```rust extern crate trust_dns_resolver; extern crate trust_dns; use std::env; use trust_dns_resolver::Resolver; use trust_dns_resolver::config::*; use trust_dns::rr::record_type::RecordType; fn main() { let args: Vec = env::args().collect(); if args.len() != 2 { eprintln!("Please provide a name to query"); std::process::exit(1); } let resolver = Resolver::new(ResolverConfig::default(), ResolverOpts::default()).unwrap(); let query = format!("{}.", args[1]); // IP address lookup let response = resolver.lookup_ip(query.as_str()); println!("Using the synchronous resolver"); for ans in response.iter() { println!("{:?}", ans); } // Using system resolver configuration let system_resolver = Resolver::from_system_conf().unwrap(); let system_response = system_resolver.lookup_ip(query.as_str()); for ans in system_response.iter() { println!("{:?}", ans); } // NS record lookup let ns = resolver.lookup(query.as_str(), RecordType::NS); println!("NS records using the synchronous resolver"); for ans in ns.iter() { println!("{:?}", ans); } } ``` -------------------------------- ### Race Futures with Timeout in Rust Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Combines multiple futures with racing and timeout semantics using select_ok and timer-based cancellation. Requires futures, futures_cpupool, tokio_timer, and rand crates. ```rust extern crate futures; extern crate futures_cpupool; extern crate tokio_timer; extern crate rand; use futures::future::select_ok; use std::time::Duration; use futures::Future; use futures_cpupool::CpuPool; use tokio_timer::Timer; use std::thread; use rand::{thread_rng, Rng}; fn player_one() -> &'static str { let d = thread_rng().gen_range::(1, 5); thread::sleep(Duration::from_secs(d)); "player_one" } fn player_two() -> &'static str { let d = thread_rng().gen_range::(1, 5); thread::sleep(Duration::from_secs(d)); "player_two" } fn main() { let pool = CpuPool::new_num_cpus(); let timer = Timer::default(); let timeout = timer.sleep(Duration::from_secs(3)).then(|_| Err(())); let one = pool.spawn_fn(|| Ok(player_one())); let two = pool.spawn_fn(|| Ok(player_two())); let tasks = vec![one, two]; let winner = select_ok(tasks).select(timeout).map(|(result, _)| result); let result = winner.wait().ok(); match result { Some(("player_one", _)) => println!("Player one won"), Some(("player_two", _)) => println!("Player two won"), Some((_, _)) | None => println!("Timed out"), } } ``` -------------------------------- ### TCP Server with JSON Protocol in Rust Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt A TCP server that uses serde for JSON serialization to create a request/response protocol. It deserializes incoming JSON messages and responds with computed results. Ensure the 'serde' and 'serde_json' crates are added to your Cargo.toml. ```rust #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; use std::net::{TcpListener, TcpStream}; use std::io::{stdin, BufRead, BufReader, Error, Write}; use std::{env, str, thread}; #[derive(Serialize, Deserialize, Debug)] struct Point3D { x: u32, y: u32, z: u32, } fn handle_client(stream: TcpStream) -> Result<(), Error> { println!("Incoming connection from: {}", stream.peer_addr()?); let mut data = Vec::new(); let mut stream = BufReader::new(stream); loop { data.clear(); let bytes_read = stream.read_until(b'\n', &mut data)?; if bytes_read == 0 { return Ok(()); } let input: Point3D = serde_json::from_slice(&data)?; let value = input.x.pow(2) + input.y.pow(2) + input.z.pow(2); write!(stream.get_mut(), "{{}} ", f64::from(value).sqrt())?; } } fn main() { let args: Vec<_> = env::args().collect(); if args[1] == "--server" { let listener = TcpListener::bind("0.0.0.0:8888").expect("Could not bind"); for stream in listener.incoming() { match stream { Err(e) => eprintln!("failed: {}", e), Ok(stream) => { thread::spawn(move || { handle_client(stream).unwrap_or_else(|error| eprintln!("{:?}", error)); }); } } } } } ``` -------------------------------- ### X25519 Diffie-Hellman Key Exchange with Ring Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Server-side implementation for establishing shared secrets using X25519 Diffie-Hellman key exchange. Requires the ring and untrusted crates. Handles client connection, key exchange, and secret derivation. ```rust // Server extern crate ring; extern crate untrusted; use std::net::{TcpListener, TcpStream}; use std::thread; use std::io::{Read, Write}; use ring::{agreement, rand}; use untrusted::Input; use ring::error::Unspecified; fn handle_client(mut stream: TcpStream) -> Result<(), Unspecified> { let rng = rand::SystemRandom::new(); // Generate server's ephemeral key pair let server_private_key = agreement::EphemeralPrivateKey::generate(&agreement::X25519, &rng)?; let mut server_public_key = [0u8; agreement::PUBLIC_KEY_MAX_LEN]; let server_public_key = &mut server_public_key[..server_private_key.public_key_len()]; server_private_key.compute_public_key(server_public_key)?; // Receive client's public key let mut peer_public_key_buf = [0u8; 32]; stream.read(&mut peer_public_key_buf).expect("Failed to read"); let peer_public_key = Input::from(&peer_public_key_buf); println!("Received: {:?}", peer_public_key); // Send server's public key stream.write(&server_public_key).expect("Failed to send server public key"); // Derive shared secret let res = agreement::agree_ephemeral( server_private_key, &agreement::X25519, peer_public_key, ring::error::Unspecified, |key_material| { let mut key = Vec::new(); key.extend_from_slice(key_material); Ok(key) } ); println!("Generated shared secret: {:?}", res.unwrap()); Ok(()) } fn main() { let listener = TcpListener::bind("0.0.0.0:8888").expect("Could not bind"); for stream in listener.incoming() { match stream { Err(e) => eprintln!("failed: {}", e), Ok(stream) => { thread::spawn(move || { handle_client(stream).unwrap_or_else(|error| eprintln!("{:?}", error)); }); } } } } ``` -------------------------------- ### Implement Custom Stream in Rust Source: https://context7.com/packtpublishing/network-programming-with-rust/llms.txt Implements the Stream trait for producing a sequence of values asynchronously, demonstrated with the Collatz conjecture sequence. Requires the futures crate. ```rust extern crate futures; use std::io; use futures::stream::Stream; use futures::{Poll, Async}; use futures::Future; #[derive(Debug)] struct CollatzStream { current: u64, end: u64, } impl CollatzStream { fn new(start: u64) -> CollatzStream { CollatzStream { current: start, end: 1 } } } impl Stream for CollatzStream { type Item = u64; type Error = io::Error; fn poll(&mut self) -> Poll, io::Error> { if self.current % 2 == 0 { self.current = self.current / 2; } else { self.current = 3 * self.current + 1; } if self.current == self.end { Ok(Async::Ready(None)) } else { Ok(Async::Ready(Some(self.current))) } } } fn main() { let stream = CollatzStream::new(10); let f = stream.for_each(|num| { println!("{}", num); Ok(()) }); f.wait().ok(); // Output: 5, 16, 8, 4, 2 } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.