use std::net::TcpStream;
use std::io::{self, Read, Write};
use std::thread;
fn main() {
println!("Enter the server address (e.g. 192.168.1.100:8080):");
let mut addr = String::new();
io::stdin().read_line(&mut addr).unwrap();
let mut stream = TcpStream::connect(addr.trim()).unwrap_or_else(|e| {
eprintln!("‌Connection failed: {} (Check the address and server status)", e);
std::process::exit(1);
});
let mut recv_stream = stream.try_clone().unwrap();
thread::spawn(move || {
let mut buffer = [0; 1024];
loop {
match recv_stream.read(&mut buffer) {
Ok(0) => {
println!("\n[System] Disconnected");
break;
}
Ok(n) => {
let msg = String::from_utf8_lossy(&buffer[..n]);
print!("\r{}> ", msg);
io::stdout().flush().unwrap();
}
Err(e) => {
eprintln!("\n[Error] Receive Failed:{}", e);
break;
}
}
}
});
loop {
let mut input = String::new();
print!("> ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut input).unwrap();
if let Err(e) = stream.write_all(input.as_bytes()) {
eprintln!("Send Failed: {}", e);
break;
}
}
}