use std::io;
use std::io::BufRead;
use std::io::Write;
use std::net;
use std::sync::mpsc;
use std::thread;
use std::time;
fn main()
{
let server_address : &str = "127.0.0.1:8888";
let (tx, rx) = mpsc::channel::<String>();
let mut tcp_stream_vector : Vec<net::TcpStream> = Vec::new();
let tcp_listener : net::TcpListener = net::TcpListener::bind(server_address).expect("서버 실행시 에러가 발생했습니다.");
tcp_listener.set_nonblocking(true).expect("넌블로킹 모드 설정시 에러가 발생했습니다.");
println!("서버 실행이 시작되었습니다 : {}", server_address);
loop
{
if let Ok((client, client_address)) = tcp_listener.accept()
{
println!("클라이언트가 접속했습니다 : {}", client_address);
tcp_stream_vector.push(client.try_clone().unwrap());
start_thread(client, tx.clone());
}
if let Ok(client_message) = rx.try_recv()
{
println!("모든 클라기언트에게 메시지 전송 : {}", client_message.trim());
tcp_stream_vector = reply_to_all_clients(tcp_stream_vector, &client_message);
}
thread::sleep(time::Duration::from_millis(100));
}
}
fn start_thread(tcp_stream : net::TcpStream, tx : mpsc::Sender<String>)
{
let mut buf_reader : io::BufReader<net::TcpStream> = io::BufReader::new(tcp_stream);
thread::spawn
(
move ||
{
loop
{
let mut message : String = String::new();
if let Ok(byte_count_read) = buf_reader.read_line(&mut message)
{
if byte_count_read > 0
{
tx.send(message).unwrap();
}
}
thread::sleep(time::Duration::from_millis(100));
}
}
);
}
fn reply_to_all_clients(tcp_stream_vector : Vec<net::TcpStream>, message : &str) -> Vec<net::TcpStream>
{
let mut new_tcp_stream_vector : Vec<net::TcpStream> = vec![];
for mut tcp_stream in tcp_stream_vector.into_iter()
{
let message_byte_vector : Vec<u8> = String::from(message).into_bytes();
if let Err(e) = tcp_stream.write_all(&message_byte_vector)
{
println!("전송시 에러가 발생했습니다 : {}", e);
continue;
}
new_tcp_stream_vector.push(tcp_stream);
}
return new_tcp_stream_vector;
}