BEGINNING RUST PROGRAMMING
Author: Ric Messier
如果需要电子书的小伙伴,可以留下邮箱,看到了会发送的
Chapter 6 Clients and Servers
这章程序的一个大纲
RUST TCP SERVER
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use bufstream::BufStream;
use std::fs;
fn make_directory(param: &str) -> String {
match fs::create_dir_all(param) {
Ok(_) => String::from("Success"),
Err(err) => err.to_string()
}
}
fn get_file_list() -> String {
let mut listing = String::with_capacity(8192);
for file in fs::read_dir(".").unwrap() {
let entry = file.unwrap().path().display().to_string();
listing.push_str(entry.as_str());
}
listing
}
fn handle_req(conn: TcpStream) {
let mut req = String::with_capacity(512);
let mut response = String::with_capacity(4096);
let mut reader = BufStream::new(&conn);
match reader.write(b"> ") {
Ok(_) => (),
Err(err) => println!("Received an error on write! {}", err)
};
let size = reader.read_line(&mut req);
if size.unwrap() > 0 {
let mut params = req.split_whitespace();
let command = params.next().unwrap();
match command {
"flist" => response = get_file_list(),
"md" => response = make_directory(params.next().unwrap()),
_ => response = "Unacceptable command"
}
match reader.write(&response.into_bytes()) {
Ok(_) => (),
Err(err) => println!("Received an error on write! {}", err)
};
}
}
fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("0.0.0.0:3333")?;
for stream in listener.incoming() {
handle_req(stream?);
}
Ok(())
}
Chapter 7 Client-Side Applications
ENCRYPTION
讲了一些加密的基础知识和算法,比如RSA、AES什么的,这里略过了,感兴趣的可以拿书看
Transport Layer Security (TLS)
使用了native-tls
这个库做TLS
use native_tls::TlsConnector;
use std::io::{Read, Write};
use std::net::TcpStream;
fn main() {
let tlsconn = TlsConnector::builder().unwrap().build().unwrap();
let tcpstream = TcpStream::connect("www.wrox.com:443").unwrap();
let mut tlsstream = tlsconn.connect("www.wrox.com", tcpstream).unwrap();
tlsstream.write_all(b"GET / HTTP/1.1\nHost: www.wrox.com\r\n\r\n").unwrap();
let mut response = vec![];
tlsstream.read_to_end(&mut response).unwrap();
println!("{}", String::from_utf8_lossy(&response));
}
use native_tls::{Identity, TlsAcceptor, TlsStream};
use std::fs::File;
use std::io::Read;
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use std::thread;
fn main() {
let mut cert = File::open("certificate.pfx").unwrap();
let mut myidentity = vec![];
cert.read_to_end(&mut myidentity).unwrap();
let certidentity = Identity::from_pkcs12(&myidentity, "passphrase").unwrap();
let tcplistener = TcpListener::bind("0.0.0.0:7999").unwrap();
let acceptor = TlsAcceptor::new(certidentity).unwrap();
let acceptor = Arc::new(acceptor);
for clientstream in tcplistener.incoming() {
match clientstream {
Ok(clientstream) => {
let acceptor = acceptor.clone();
thread::spawn(move || {
let clientstream = acceptor.accept(clientstream).unwrap();
/* do something here using clientstream */
});
}
Err(e) => { /* connection failed */ }
}
}
}
REMOTE ACCESS CLIENT
对应上一章的server,写出来的client
use std::io::prelude::*;
use std::net::TcpStream;
use std::env;
use std::io;
use regex::Regex;
fn validate_input(input: &String) -> bool {
let mut valid: bool = false;
let mut params = input.split_whitespace();
let command = params.next().unwrap();
match command {
"flist" => valid = true,
"md" => valid = true,
_ => valid = false
}
valid
}
fn handle_input(mut serverstream: TcpStream) {
let mut recvstring = [0; 4096];
let mut keepgoing: bool = true;
let re = Regex::new(r"^[eE][xX][iI][tT]$").unwrap();
let mut size = serverstream.read(&mut recvstring);
println!("{}", String::from_utf8_lossy(&recvstring));
while keepgoing {
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(_n) => {
input = input.trim().to_string();
if re.is_match(input.as_str()) {
keepgoing = false;
}
else {
if validate_input(&input) {
match serverstream.write(&input.as_bytes()) {
Ok(_n) => { () },
Err(_e) => {
panic!("Unable to write to server");
}
}
}
else {
println!("Not a valid command");
}
size = serverstream.read(&mut recvstring);
println!("{}", String::from_utf8_lossy(&recvstring));
}
}
Err(error) => println!("error: {}", error),
}
}
}
fn main() {
let args: Vec<String> = env::args().collect();
let serverstring = &args[1];
match TcpStream::connect(serverstring) {
Ok(mut serverstream) => {
println!("Successfully connected to {}", serverstring);
handle_input(serverstream);
},
Err(e) => {
panic!("Unable to connect to {}", serverstring);
}
}
}
标签:std,mut,use,unwrap,PROGRAMMING,---,let,input,随记
From: https://www.cnblogs.com/huangwenhao1024/p/16927124.html