Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::net::TcpListener;
- use std::io::{Read, Write};
- use tokio::sync::broadcast;
- #[tokio::main]
- async fn main() {
- let listener = TcpListener::bind("127.0.0.1:8080").expect("failed to start server");
- println!("listening at 127.0.0.1:8080");
- let (tx, rx) = broadcast::channel::<String>(64);
- for stream in listener.incoming() {
- match stream {
- Ok(mut connection) => {
- let tx2 = tx.clone();
- let mut rx2 = rx.resubscribe();
- tokio::spawn(async move {
- let mut buf = [0; 1024];
- let n = connection.read(&mut buf).unwrap();
- let username = String::from_utf8_lossy(&buf[..n]).to_string();
- println!("{username} has joined");
- let mut connection2 = connection.try_clone().unwrap();
- let receiver_task = tokio::spawn(async move {
- while let Ok(m) = rx2.recv().await {
- connection2.write_all(m.as_bytes()).unwrap();
- }
- });
- let sender_task = tokio::spawn(async move {
- loop {
- let mut buf = [0; 1024];
- let n = connection.read(&mut buf).unwrap();
- let output = format!("{username}: {}", String::from_utf8_lossy(&buf[..n]).to_string());
- println!("{output}");
- let _ = tx2.send(output).unwrap();
- }
- });
- let _ = sender_task.await;
- receiver_task.abort();
- });
- }
- Err(e) => eprintln!("Error: {e}"),
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement