4

solucion proyecto final

Sebastian
satica
18319

esta es la solución completa del proyecto, la estructura debe quedar asi:
https://ibb.co/cc94JML
src/bin/main.rs
debe quedar asi:

use NombreProyecto::ThreadPool;
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;

fnmain() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
    let pool = ThreadPool::new(4);

    for stream in listener.incoming().take(2) {
        let stream = stream.unwrap();

        pool.execute(|| {
            handle_connection(stream);
        });
    }

    println!("Shutting down.");
}

fnhandle_connection(mut stream: TcpStream) {
    letmut buffer = [0; 1024];
    stream.read(&mut buffer).unwrap();

    let get = b"GET / HTTP/1.1\r\n";
    let sleep = b"GET /sleep HTTP/1.1\r\n";

    let (status_line, filename) = if buffer.starts_with(get) {
        ("HTTP/1.1 200 OK\r\n\r\n", "index.html")
    } elseif buffer.starts_with(sleep) {
        thread::sleep(Duration::from_secs(5));
        ("HTTP/1.1 200 OK\r\n\r\n", "index.html")
    } else {
        ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
    };

    let contents = fs::read_to_string(filename).unwrap();

    let response = format!("{}{}", status_line, contents);

    stream.write(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}

src/lib.rs
debe quedar asi:

use std::sync::mpsc;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;

pubstructThreadPool {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Message>,
}

typeJob = Box<dyn FnOnce() + Send + 'static>;

enumMessage {
    NewJob(Job),
    Terminate,
}

impl ThreadPool {
    /// Create a new ThreadPool.////// The size is the number of threads in the pool.////// # Panics////// The `new` function will panic if the size is zero.pubfnnew(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let receiver = Arc::new(Mutex::new(receiver));

        letmut workers = Vec::with_capacity(size);

        for id in0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool { workers, sender }
    }

    pubfnexecute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);

        self.sender.send(Message::NewJob(job)).unwrap();
    }
}

implDropfor ThreadPool {
    fndrop(&mutself) {
        println!("Sending terminate message to all workers.");

        for _ in &self.workers {
            self.sender.send(Message::Terminate).unwrap();
        }

        println!("Shutting down all workers.");

        for worker in &mutself.workers {
            println!("Shutting down worker {}", worker.id);

            ifletSome(thread) = worker.thread.take() {
                thread.join().unwrap();
            }
        }
    }
}

structWorker {
    id: usize,
    thread: Option<thread::JoinHandle<()>>,
}

impl Worker {
    fnnew(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Message>>>) -> Worker {
        let thread = thread::spawn(move || loop {
            let message = receiver.lock().unwrap().recv().unwrap();

            match message {
                Message::NewJob(job) => {
                    println!("Worker {} got a job; executing.", id);

                    job();
                }
                Message::Terminate => {
                    println!("Worker {} was told to terminate.", id);

                    break;
                }
            }
        });

        Worker {
            id,
            thread: Some(thread),
        }
    }
}

fnmain() {}

en el main.rs debe ser el nombre del proyecto el que reemplaza “NombreProyecto”.
luego desde console por fuera del directorio , cargo run , notese que en este ejemplo se cambia el puerto por el 7878, esto es porque todo el ejemplo y proyecto es tomado de la documentacion de mozilla, https://doc.rust-lang.org/book/ch20-00-final-project-a-web-server.html

me funciono sin problema,

https://ibb.co/JmgY7Gh
Escribe tu comentario
+ 2
Ordenar por:
1
57291Puntos

No todos los héroes llevan capa. Gracias…