1
0
Fork 0
mirror of https://github.com/dadada/portfs.git synced 2025-06-08 01:53:56 +02:00

Rewrite with tokio

This commit is contained in:
Tim Schubert 2019-06-01 18:12:07 +02:00
parent 38e6841f53
commit c872351556
3 changed files with 729 additions and 39 deletions

View file

@ -1,43 +1,44 @@
use std::net::{TcpListener, TcpStream, SocketAddr};
use std::io::Result;
use std::fs::File;
use std::io::Write;
use std::io;
extern crate tokio;
use std::path::Path;
use tokio::fs::File;
use tokio::io::copy;
use tokio::net::{TcpListener, TcpStream};
use tokio::prelude::*;
use tokio::prelude::{AsyncRead, Future};
fn handle_client(mut stream: TcpStream, addr: SocketAddr) {
println!("Received connection from {:?}", addr.port());
let mut filename = addr.port().to_string();
if Path::new(&filename).exists() {
let mut buffer = File::open(&filename).unwrap();
match io::copy(&mut buffer, &mut stream) {
Ok(_written) => (),
Err(e) => println!("Failed to file {:?} to TCP stream: {:?}", filename, e),
}
} else {
let mut buffer = File::create(&filename).unwrap();
match io::copy(&mut stream, &mut buffer) {
Ok(_written) => {
filename.push('\n');
match stream.write_all(filename.as_bytes()) {
Err(e) => println!("Error writing to socket {:?}", e),
_ => (),
}
fn main() {
let addr = "127.0.0.1:8080".parse().unwrap();
let listener = TcpListener::bind(&addr).expect("unable to bind TCP listener");
let server = listener
.incoming()
.map_err(|e| eprintln!("accept failed = {:?}", e))
.for_each(|sock| {
let addr = sock.peer_addr().unwrap();
println!("Received connection from {:?}", addr.port());
let filename = addr.port().to_string();
let path = Path::new(&filename);
let (reader, writer) = sock.split();
if path.exists() {
let task = File::open(filename)
.and_then(|file| copy(file, writer))
.map(|res| println!("{:?}", res))
.map_err(|err| eprintln!("IO error: {:?}", err));
tokio::spawn(task)
} else {
let task = File::create(filename)
.and_then(|file| copy(reader, file))
.map(|res| println!("{:?}", res))
.map_err(|err| eprintln!("IO error: {:?}", err));
tokio::spawn(task)
}
Err(e) => println!("Failed to write TCP stream to file {:?} failed with {:?}", filename, e),
}
}
}
fn main() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:8080")?;
// accept connections and process them serially
loop {
match listener.accept() {
Ok((socket, addr)) => handle_client(socket, addr),
Err(e) => println!("could not accept client: {:?}", e),
}
}
});
// Start the Tokio runtime
tokio::run(server);
}