序列化到 json yaml
// Serde crate 是 Serde 生态的核心。
// serde_derive crate 提供的必要工具,
// 使用过程宏来派生 Serialize 和 Deserialize
// 使用 serde 只提供序列化和反序列化的框架,具体的操作还需要依赖具体的包。
// 如 serde_json、serde_toml 等
// serde = { version = "1.0.125", features = ["derive"] } 该方式可以不使用 serde_derive
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct ServerConfig {
workers: u64,
ignore: bool,
auth_server: Option<String>,
}
fn main() {
let config = ServerConfig {
workers: 8,
ignore: true,
auth_server: Some("auth.server.io".to_string()),
};
{
println!("json");
let serialized = serde_json::to_string(&config).unwrap();
println!("json: {}", serialized);
let deserialzied: ServerConfig = serde_json::from_str(&serialized).unwrap();
println!("config: {:#?}", deserialzied);
}
{
println!("yaml");
let serialized = serde_yaml::to_string(&config).unwrap();
println!("yaml: {}", serialized);
let deserialzied: ServerConfig = serde_yaml::from_str(&serialized).unwrap();
println!("config: {:#?}", deserialzied);
}
}
// 可以实现自定义 serialize deserialize trait
一个 demo
客户端将一个结构体序列化后发送到服务端
server.rs
use serde::{Deserialize, Serialize};
use serde_json;
use std::io::{self, prelude::*, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::{str, thread};
#[derive(Debug, Deserialize, Serialize)]
struct Point3D {
x: i32,
y: i32,
z: i32,
}
fn handle_client(stream: TcpStream) -> io::Result<()> {
println!("incomming connenction from : {}", stream.peer_addr()?);
let mut buffer = Vec::new();
let mut stream = BufReader::new(stream);
loop {
buffer.clear();
let bytes_read = stream.read_until(b'\n', &mut buffer)?;
if bytes_read == 0 {
return Ok(());
}
let input: Point3D = serde_json::from_slice(&buffer)?;
let value = input.x.pow(2) + input.y.pow(2) + input.z.pow(2);
let value = serde_json::to_vec(&f64::from(value).sqrt())?;
stream.get_mut().write(&value)?;
stream.get_mut().write("\n".as_bytes())?;
stream.get_mut().flush()?;
}
}
fn main() -> io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:8080")?;
for stream in listener.incoming() {
match stream {
Err(e) => println!("error: {}", e),
Ok(stream) => {
thread::spawn(move || {
handle_client(stream).unwrap_or_else(|error| eprint!("error:{:?}", error));
});
}
}
}
Ok(())
}
client.rs
use serde::{Deserialize, Serialize};
use serde_json;
use std::io::{self, prelude::*, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::{str, thread};
#[derive(Debug, Deserialize, Serialize)]
struct Point3D {
x: i32,
y: i32,
z: i32,
}
fn main() -> anyhow::Result<()> {
let mut stream = TcpStream::connect("127.0.0.1:8080")?;
loop {
let mut input = String::new();
let mut buffer = Vec::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read from stdin");
let parts: Vec<&str> = input.trim_matches('\n').split(',').collect();
let point = Point3D {
x: parts[0].parse().unwrap(),
y: parts[1].parse().unwrap(),
z: parts[2].parse().unwrap(),
};
stream
.write_all(serde_json::to_string(&point).unwrap().as_bytes())
.expect("failed to write");
stream.write_all(b"\n")?;
let mut reader = BufReader::new(&stream);
reader.read_until(b'\n', &mut buffer)?;
let input = str::from_utf8(&buffer)?;
if input == "" {
eprintln!("Empty response");
}
println!("response ::{}", input);
}
}