Skip to content

Instantly share code, notes, and snippets.

@darotar
Created October 20, 2021 16:01
Show Gist options
  • Save darotar/e13d9f2ef981414ba8469ab187381b6c to your computer and use it in GitHub Desktop.
Save darotar/e13d9f2ef981414ba8469ab187381b6c to your computer and use it in GitHub Desktop.
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