首页 技术 正文
技术 2022年11月19日
0 收藏 803 点赞 4,649 浏览 2862 个字

[易学易懂系列|rustlang语言|零基础|快速入门|(26)|实战3:Http服务器(多线程版本)]

项目实战

实战3:Http服务器

我们今天来进一步开发我们的Http服务器,用多线程实现。

我们在原来工程h_server更新代码如下:

src/main.rs:

use h_server::*;
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
println!("multi-threads server is up!");
for stream in listener.incoming() {
let stream = stream.unwrap();
println!("multi-threads server get request!");
pool.execute(|| {
handle_connection(stream);
});
}
}
fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 512];
stream.read(&mut buffer).unwrap(); let get = b"GET / HTTP/1.1\r\n"; let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK\r\n\r\n", "hello.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:

use std::sync::mpsc;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;enum Message {
NewJob(Job),
Terminate,
}pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Message>,
}trait FnBox {
fn call_box(self: Box<Self>);
}impl<F: FnOnce()> FnBox for F {
fn call_box(self: Box<F>) {
(*self)()
}
}type Job = Box<dyn FnBox + Send + 'static>;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.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
} ThreadPool { workers, sender }
} pub fn execute<F>(&self, f: F)
where
//这里定义闭包,是FnOnce类型,代表一个线程只运行一次
//Send类型,代表闭包可以在不同线程中传递
//'static,代表闭包生命周期跟整个程序一样
F: FnOnce() + Send + 'static,
{
let job = Box::new(f); self.sender.send(Message::NewJob(job)).unwrap();
}
}
//实现Drop特征,用于处理资源释放相关逻辑
impl Drop for ThreadPool {
fn drop(&mut self) {
println!("Sending terminate message to all workers."); for _ in &mut self.workers {
self.sender.send(Message::Terminate).unwrap();
} println!("Shutting down all workers."); for worker in &mut self.workers {
println!("Shutting down worker {}", worker.id); if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}impl Worker {
fn new(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.call_box();
}
Message::Terminate => {
println!("Worker {} was told to terminate.", id); break;
}
}
}); Worker {
id,
thread: Some(thread),
}
}
}

直接运行命令:

cargo run

启动服务器。

然后用浏览器访问:

http://127.0.0.1:7878/

页面显示:

Hello!Hi from Rust

以上,希望对你有用。

如果遇到什么问题,欢迎加入:rust新手群,在这里我可以提供一些简单的帮助,加微信:360369487,注明:博客园+rust

参考文章:

https://doc.rust-lang.org/stable/book/ch20-02-multithreaded.html

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,999
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,511
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,357
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,140
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848