77 lines
2.6 KiB
Rust
77 lines
2.6 KiB
Rust
use std::net::{TcpListener, TcpStream};
|
|
use std::io::{BufRead, BufReader, Write};
|
|
use std::thread;
|
|
|
|
|
|
fn handle_client(mut stream: TcpStream) {
|
|
// Read and print client input
|
|
let mut reader = BufReader::new(&stream);
|
|
loop {
|
|
let mut buffer = String::new();
|
|
reader.read_line(&mut buffer).expect("Read error");
|
|
if buffer.is_empty() {
|
|
break;
|
|
}
|
|
println!("Received: {}", buffer.trim());
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
// Listen for incoming connections on port 8080
|
|
let listener = TcpListener::bind("127.0.0.1:8080").expect("Listen error");
|
|
|
|
// Store client connections in a vector
|
|
let mut clients: Vec<TcpStream> = Vec::new();
|
|
|
|
// Accept incoming connections and spawn a new thread for each client
|
|
for stream in listener.incoming() {
|
|
match stream {
|
|
Ok(stream) => {
|
|
println!("New client connected: {:?}", stream.peer_addr().unwrap());
|
|
clients.push(stream.try_clone().expect("Clone error"));
|
|
let mut client_idx = clients.len() - 1;
|
|
thread::spawn(move || {
|
|
handle_client(stream);
|
|
println!("Client disconnected: {:?}", clients[client_idx].peer_addr().unwrap());
|
|
clients.remove(client_idx);
|
|
});
|
|
}
|
|
Err(e) => {
|
|
println!("Connection error: {:?}", e);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Allow the user to switch between connections
|
|
loop {
|
|
let mut input = String::new();
|
|
std::io::stdin().read_line(&mut input).expect("Read error");
|
|
match input.trim() {
|
|
"list" => {
|
|
println!("Connected clients:");
|
|
for (idx, client) in clients.iter().enumerate() {
|
|
println!("{}: {:?}", idx, client.peer_addr().unwrap());
|
|
}
|
|
}
|
|
"switch" => {
|
|
println!("Enter client index:");
|
|
let mut input = String::new();
|
|
std::io::stdin().read_line(&mut input).expect("Read error");
|
|
let client_idx = input.trim().parse::<usize>().expect("Parse error");
|
|
if client_idx < clients.len() {
|
|
// TODO: Switch to selected client
|
|
println!("Switching to client: {:?}", clients[client_idx].peer_addr().unwrap());
|
|
} else {
|
|
println!("Invalid client index");
|
|
}
|
|
}
|
|
"exit" => {
|
|
break;
|
|
}
|
|
_ => {
|
|
println!("Invalid command");
|
|
}
|
|
}
|
|
}
|
|
}
|