Loading rust_07_communication...
fn main() { for arg in std::env::args() { println!("{:?}", arg); } } /* "target/debug/my_project" "hello" "123" "voila" */
fn main() { let args = Vec::from_iter(std::env::args()); println!("{:?}", args); } /* ["target/debug/my_project", "hello", "123", "voila"] */
rustup doc --book“12.1. Accepting Command Line Arguments”
rustup doc --rust-by-example“20.7. Program arguments”
rustup doc --std 'std::env::args'
rustup doc --std 'std::iter::Iterator'
fn main() -> Result<(), Box<dyn std::error::Error>> { let file_name = "my_file.txt"; // prepare some text let prepared_string = format!("Here are\nsome very\ninteresting words\n"); let prepared_bytes = prepared_string.as_bytes();
// store this sequence of bytes in the file std::fs::write(file_name, prepared_bytes)?;
// read back a sequence of bytes from the file let obtained_bytes = std::fs::read(file_name)?; if obtained_bytes == prepared_bytes { println!("got the same bytes"); } let obtained_str = std::str::from_utf8(&obtained_bytes)?; if obtained_str == prepared_string { println!("thus the same string"); } println!("obtained_str={:?}", obtained_str); Ok(()) } /* got the same bytes thus the same string obtained_str="Here are\nsome very\ninteresting words\n" */
use std::{ fs::File, io::{BufRead, BufReader, BufWriter, Write}, };
fn write_lines( path: &str, values: &[f32], ) -> Result<(), Box<dyn std::error::Error>> { let mut output = BufWriter::new(File::create(path)?); for value in values.iter() { // write each real value ... writeln!(output, "{}", value)?; // ... as a text line } Ok(()) }
fn read_lines(path: &str) -> Result<Vec<f32>, Box<dyn std::error::Error>> { let mut values = Vec::new(); let input = BufReader::new(File::open(path)?); for line in input.lines().filter_map(|l| l.ok()) { println!("line {:?}", line); if let Ok(value) = line.parse() { // try to interpret this text ... values.push(value); // ... line as a real value } } Ok(values) }
fn main() -> Result<(), Box<dyn std::error::Error>> { let file_name = "my_file.txt"; let prepared_values = [1.1, 2.2, 3.3]; write_lines(file_name, &prepared_values)?; let obtained_values = read_lines(file_name)?; if obtained_values == prepared_values { println!("got the same values"); } println!("values={:?}", obtained_values); Ok(()) } /* line "1.1" line "2.2" line "3.3" got the same values values=[1.1, 2.2, 3.3] */
use std::{ fs::File, io::{BufReader, BufWriter, Read, Write}, };
fn write_binary( path: &str, values: &[f32], ) -> Result<(), Box<dyn std::error::Error>> { let mut output = BufWriter::new(File::create(path)?); for value in values.iter() { let bytes = value.to_le_bytes(); // write each real value ... output.write_all(&bytes)?; // ... as its constitutive bytes } Ok(()) }
fn read_binary(path: &str) -> Result<Vec<f32>, Box<dyn std::error::Error>> { let mut values = Vec::new(); let mut input = BufReader::new(File::open(path)?); let mut bytes = [0_u8; std::mem::size_of::<f32>()]; // prepare storage, ... while input.read_exact(&mut bytes).is_ok() { // ... extract bytes and ... values.push(f32::from_le_bytes(bytes)); // ... consider as a real value } Ok(values) }
fn main() -> Result<(), Box<dyn std::error::Error>> { let file_name = "my_file.bin"; let prepared_values = [1.1, 2.2, 3.3]; write_binary(file_name, &prepared_values)?; let obtained_values = read_binary(file_name)?; if obtained_values == prepared_values { println!("got the same values"); } println!("values={:?}", obtained_values); Ok(()) } /* got the same values values=[1.1, 2.2, 3.3] */
rustup doc --rust-by-example“20.4. File I/O”
rustup doc --std 'std::fs::write',
rustup doc --std 'std::fs::read',
rustup doc --std 'std::fs::File'
rustup doc --std 'std::io::BufWriter',
rustup doc --std 'std::io::Write',
rustup doc --std 'std::writeln!'
rustup doc --std 'std::io::BufReader',
rustup doc --std 'std::io::BufRead',
rustup doc --std 'std::io::Read'
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)] struct Stat { name: String, values: Vec<f32>, }
fn main() -> Result<(), Box<dyn std::error::Error>> { let prepared_stats = vec![ Stat { name: "age".to_owned(), values: vec![37.0, 51.0, 46.0, 28.0], }, Stat { name: "BMI".to_owned(), values: vec![28.2, 21.3, 18.4, 20.4], }, ]; println!("prepared_stats:\n {:?}", prepared_stats);
let json_serialised_stats = serde_json::to_string(&prepared_stats)?; println!("json_serialised_stats:\n {}", json_serialised_stats);
let deserialised_stats = serde_json::from_str::<Vec<Stat>>(&json_serialised_stats)?; println!("deserialised_stats:\n {:?}", deserialised_stats); Ok(()) } /* prepared_stats: [Stat { name: "age", values: [37.0, 51.0, 46.0, 28.0] }, Stat { name: "BMI", values: [28.2, 21.3, 18.4, 20.4] }] json_serialised_stats: [{"name":"age","values":[37.0,51.0,46.0,28.0]},{"name":"BMI","values":[28.2,21.3,18.4,20.4]}] deserialised_stats: [Stat { name: "age", values: [37.0, 51.0, 46.0, 28.0] }, Stat { name: "BMI", values: [28.2, 21.3, 18.4, 20.4] }] */
[dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = "1.0"
use std::{ io::{BufRead, BufReader, Write}, net::TcpStream, };
fn main() -> Result<(), Box<dyn std::error::Error>> { let args = Vec::from_iter(std::env::args()); let server_name = args.get(1).ok_or("missing server name")?.as_str(); let server_port = args.get(2).ok_or("missing server port")?.parse::<u16>()?;
println!("connecting to server {}:{}", server_name, server_port); let stream = TcpStream::connect((server_name, server_port))?; let mut output = stream.try_clone()?; let mut input = BufReader::new(stream);
for word in ["12", "-4", "hop", "3"] { std::thread::sleep(std::time::Duration::from_millis(1000));
let request = format!("{}\n", word); println!("\nsending request {:?} to server...", request); output.write_all(request.as_bytes())?;
println!("waiting for reply from server..."); let mut reply = String::new(); let r = input.read_line(&mut reply)?; if r == 0 { println!("EOF"); break; }
println!("obtained {:?} from server", reply); if let Ok(value) = reply.trim().parse::<i32>() { println!("~~> {}", value); } } Ok(()) } /* connecting to server localhost:9988
sending request "12\n" to server... waiting for reply from server... obtained "144\n" from server ~~> 144
sending request "-4\n" to server... waiting for reply from server... obtained "16\n" from server ~~> 16
sending request "hop\n" to server... waiting for reply from server... obtained "invalid request: invalid digit found in string\n" from server
sending request "3\n" to server... waiting for reply from server... obtained "9\n" from server ~~> 9 */
use std::{ io::{BufRead, BufReader, Write}, net::{Ipv4Addr, TcpListener, TcpStream}, };
fn main() -> Result<(), Box<dyn std::error::Error>> { let args = Vec::from_iter(std::env::args()); let tcp_port = args.get(1).ok_or("missing port number")?.parse::<u16>()?; let listener = TcpListener::bind((Ipv4Addr::UNSPECIFIED, tcp_port))?; println!("tcp server waiting for connections on port '{}'", tcp_port);
for incoming in listener.incoming() { let stream = incoming?; println!("new connection from {:?}", stream.peer_addr()?); std::thread::spawn(move || { if let Err(e) = handle_connection(stream) { eprintln!("ERROR: {}", e); } }); } Ok(()) }
fn handle_connection( stream: TcpStream ) -> Result<(), Box<dyn std::error::Error>> { let mut output = stream.try_clone()?; let mut input = BufReader::new(stream); loop { println!("\nwaiting for request from client..."); let mut request = String::new(); let r = input.read_line(&mut request)?; if r == 0 { println!("EOF"); break; }
println!("obtained {:?} from client", request); let reply = match request.trim().parse::<i32>() { Ok(value) => format!("{}\n", value * value), Err(e) => format!("invalid request: {}\n", e), };
println!("sending reply {:?} to client...", reply); output.write_all(reply.as_bytes())?; } Ok(()) }
/* tcp server waiting for connections on port '9988' new connection from 127.0.0.1:40880
waiting for request from client... obtained "12\n" from client sending reply "144\n" to client...
waiting for request from client... obtained "-4\n" from client sending reply "16\n" to client...
waiting for request from client... obtained "hop\n" from client sending reply "invalid request: invalid digit found in string\n" to client...
waiting for request from client... obtained "3\n" from client sending reply "9\n" to client...
waiting for request from client... EOF */
rustup doc --std 'std::future').