Created
October 20, 2021 16:01
-
-
Save darotar/e13d9f2ef981414ba8469ab187381b6c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use tokio::{ | |
io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, | |
net::TcpListener, | |
sync::broadcast, | |
}; | |
#[tokio::main] | |
async fn main() { | |
let listener = TcpListener::bind("localhost:8080").await.unwrap(); | |
let (tx, _rx) = broadcast::channel(10); | |
loop { | |
let (mut socket, addr) = listener.accept().await.unwrap(); | |
let tx = tx.clone(); | |
let mut rx = tx.subscribe(); | |
tokio::spawn(async move { | |
let (reader, mut writer) = socket.split(); | |
let mut reader = BufReader::new(reader); | |
let mut line = String::new(); | |
loop { | |
tokio::select! { | |
result = reader.read_line(&mut line) => { | |
if result.unwrap() == 0 { | |
break; | |
} | |
tx.send((line.clone(), addr)).unwrap(); | |
line.clear(); | |
} | |
result = rx.recv() => { | |
let (msg, other_addr) = result.unwrap(); | |
if addr != other_addr { | |
writer.write_all(msg.as_bytes()).await.unwrap(); | |
} | |
} | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment