Advertisement
Guest User

Untitled

a guest
Mar 11th, 2024
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.81 KB | Source Code | 0 0
  1. use std::net::TcpListener;
  2. use std::io::{Read, Write};
  3.  
  4. use tokio::sync::broadcast;
  5.  
  6. #[tokio::main]
  7. async fn main() {
  8.     let listener = TcpListener::bind("127.0.0.1:8080").expect("failed to start server");
  9.     println!("listening at 127.0.0.1:8080");
  10.  
  11.     let (tx, rx) = broadcast::channel::<String>(64);
  12.  
  13.  
  14.     for stream in listener.incoming() {
  15.         match stream {
  16.             Ok(mut connection) => {
  17.                 let tx2 = tx.clone();
  18.                 let mut rx2 = rx.resubscribe();
  19.                 tokio::spawn(async move {
  20.                     let mut buf = [0; 1024];
  21.                     let n = connection.read(&mut buf).unwrap();
  22.  
  23.                     let username = String::from_utf8_lossy(&buf[..n]).to_string();
  24.                     println!("{username} has joined");
  25.  
  26.                     let mut connection2 = connection.try_clone().unwrap();
  27.                     let receiver_task = tokio::spawn(async move {
  28.                         while let Ok(m) = rx2.recv().await {
  29.                             connection2.write_all(m.as_bytes()).unwrap();
  30.                         }
  31.                     });
  32.  
  33.                     let sender_task = tokio::spawn(async move {
  34.                         loop {
  35.                             let mut buf = [0; 1024];
  36.                             let n = connection.read(&mut buf).unwrap();
  37.  
  38.                             let output = format!("{username}: {}", String::from_utf8_lossy(&buf[..n]).to_string());
  39.                             println!("{output}");
  40.                             let _ = tx2.send(output).unwrap();
  41.                         }
  42.                     });
  43.  
  44.                     let _ = sender_task.await;
  45.                     receiver_task.abort();
  46.                 });
  47.             }
  48.             Err(e) => eprintln!("Error: {e}"),
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement