|
| 1 | +use colored::Colorize; |
| 2 | +use ghost_sync::{Client, ServerEvent}; |
| 3 | +use std::env; |
| 4 | +use tokio::io::{AsyncBufReadExt, BufReader}; |
| 5 | + |
| 6 | +/// Very basic chatroom client. Connects to the server, joins a room, and broadcasts lines from stdin to all peers. |
| 7 | +#[tokio::main] |
| 8 | +async fn main() -> anyhow::Result<()> { |
| 9 | + let name = env::args().nth(1).unwrap_or_else(|| { |
| 10 | + eprintln!("Usage: chatroom <name> <addr>"); |
| 11 | + std::process::exit(1); |
| 12 | + }); |
| 13 | + let addr = env::args().nth(2).unwrap_or_else(|| { |
| 14 | + eprintln!("Usage: chatroom <name> <addr>"); |
| 15 | + std::process::exit(1); |
| 16 | + }); |
| 17 | + |
| 18 | + let mut client = Client::connect(addr.as_str()).await?; |
| 19 | + client.join("chatroom").await?; |
| 20 | + |
| 21 | + // Wait for join confirmation |
| 22 | + match client.recv().await? { |
| 23 | + Some(ServerEvent::Joined { client_id, room_id }) => { |
| 24 | + println!("Joined room '{room_id}' as {name} (id: {client_id})"); |
| 25 | + } |
| 26 | + _ => { |
| 27 | + eprintln!("Unexpected response from server"); |
| 28 | + return Ok(()); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + let stdin = BufReader::new(tokio::io::stdin()); |
| 33 | + let mut lines = stdin.lines(); |
| 34 | + |
| 35 | + loop { |
| 36 | + tokio::select! { |
| 37 | + // Read from stdin |
| 38 | + result = lines.next_line() => { |
| 39 | + match result { |
| 40 | + Ok(Some(text)) if !text.is_empty() => { |
| 41 | + // Show our own message locally |
| 42 | + // println!("[{name}]: {text}"); |
| 43 | + // Broadcast to peers |
| 44 | + let msg = format!("{name}: {text}"); |
| 45 | + client.broadcast(msg.as_bytes()).await?; |
| 46 | + } |
| 47 | + _ => break, // EOF |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + // Receive from server |
| 52 | + result = client.recv() => { |
| 53 | + match result { |
| 54 | + #[allow(clippy::single_match)] |
| 55 | + Ok(Some(event)) => match event { |
| 56 | + ServerEvent::Broadcast { data, .. } => { |
| 57 | + let text = String::from_utf8_lossy(&data); |
| 58 | + println!("{text}"); |
| 59 | + } |
| 60 | + // ServerEvent::PlayerJoined { client_id } => { |
| 61 | + // println!(">> {client_id} joined the room"); |
| 62 | + // } |
| 63 | + // ServerEvent::PlayerLeft { client_id } => { |
| 64 | + // println!(">> {client_id} left the room"); |
| 65 | + // } |
| 66 | + _ => {} |
| 67 | + }, |
| 68 | + Ok(None) => { |
| 69 | + println!("{}","Disconnected from server.".red()); |
| 70 | + break; |
| 71 | + } |
| 72 | + Err(e) => { |
| 73 | + eprintln!("Error: {e}"); |
| 74 | + break; |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + Ok(()) |
| 82 | +} |
0 commit comments