Created
October 17, 2018 02:54
-
-
Save Leonti/03057b9c11afb3fcc1ea2ee60d6d7bb9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(unused)] | |
use std::io::Write; | |
use std::io; | |
use std::net::{TcpListener, TcpStream}; | |
use std::thread; | |
use std::time; | |
use std::sync::{Arc,RwLock}; | |
// https://github.com/Nervengift/chat-server-example/blob/master/src/main.rs | |
fn handle_client(mut stream: TcpStream, arc: Arc<RwLock<Vec<String>>>) { | |
println!("Client connected"); | |
loop { | |
{ | |
let lines = arc.read().unwrap(); | |
println!("DEBUG arc.read() => {:?}", lines); | |
for line in lines.iter() { | |
stream.write_fmt(format_args!("{}", line)).unwrap(); | |
}; | |
} | |
} | |
} | |
fn main() -> io::Result<()> { | |
let arc: Arc<RwLock<Vec<String>>> = Arc::new(RwLock::new(Vec::new())); | |
let arc_w = arc.clone(); | |
thread::spawn(move|| { | |
loop { | |
{ | |
let mut arc_w = arc_w.write().unwrap(); | |
arc_w.clear(); | |
arc_w.push("test message".to_string()); | |
thread::sleep(time::Duration::from_millis(500)); | |
} // write lock is released at the end of this scope | |
} | |
}); | |
let listener = TcpListener::bind("127.0.0.1:9999")?; | |
for stream in listener.incoming() { | |
let arc = arc.clone(); | |
thread::spawn(|| { | |
handle_client(stream.unwrap(), arc); | |
}); | |
} | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment