add counter for coolness

This commit is contained in:
AJ ONeal 2018-10-01 20:24:19 -06:00
parent f38b547408
commit 1605934dbb
1 changed files with 17 additions and 3 deletions

View File

@ -2,25 +2,39 @@ use std::io::prelude::*;
use std::fs;
use std::net::TcpStream;
use std::net::TcpListener;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let counter = Arc::new(Mutex::new(0usize));
//let pool = ThreadPool::new(100);
for stream in listener.incoming() {
let stream = stream.unwrap();
let counter = Arc::clone(&counter);
handle_connection(stream);
thread::spawn(move || {
{
let mut count = counter.lock().unwrap();
*count += 1;
}
handle_connection(counter, stream);
});
}
}
fn handle_connection(mut stream: TcpStream) {
fn handle_connection(counter: Arc<Mutex<usize>>, mut stream: TcpStream) {
let mut buffer = [0; 512];
stream.read(&mut buffer).unwrap();
println!("Request: {}", String::from_utf8_lossy(&buffer[..]));
{
let count = counter.lock().unwrap();
println!("Request: {}\n{}", count, String::from_utf8_lossy(&buffer[..]));
}
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";