Skip to content

Instantly share code, notes, and snippets.

@ssrlive
Created September 29, 2021 08:21
Show Gist options
  • Save ssrlive/c668e9d6a62114ae81fe83170483f5cd to your computer and use it in GitHub Desktop.
Save ssrlive/c668e9d6a62114ae81fe83170483f5cd to your computer and use it in GitHub Desktop.
chat demo in rust
use std::net::SocketAddr;
// tokio = { version = "1.12.0", features = ["full" ] }
use tokio::{
io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
net::TcpListener,
sync::broadcast,
};
#[tokio::main]
async fn main() {
let listener = TcpListener::bind("localhost:8000").await.unwrap();
let (tx, _) = broadcast::channel::<(String, SocketAddr)>(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