made a simple echo chat server
This commit is contained in:
parent
ebaa596a2d
commit
24e9621194
1 changed files with 35 additions and 13 deletions
44
src/main.rs
44
src/main.rs
|
@ -1,8 +1,7 @@
|
|||
use anyhow::Result;
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
use deck::Deck;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
mod card;
|
||||
mod deck;
|
||||
|
@ -11,18 +10,41 @@ mod lobby;
|
|||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), anyhow::Error> {
|
||||
let listener = TcpListener::bind("127.0.0.1:6379").await?;
|
||||
let address = "127.0.0.1:8080".to_string();
|
||||
let listener = TcpListener::bind(&address).await?;
|
||||
|
||||
let (tx, rx) = broadcast::channel::<String>(10);
|
||||
|
||||
while let Ok((mut stream,_)) = listener.accept().await {
|
||||
let tx = tx.clone();
|
||||
let mut rx = rx.resubscribe();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let (read, mut write) = stream.split();
|
||||
let mut reader = BufReader::new(read);
|
||||
let mut line = String::new();
|
||||
|
||||
loop {
|
||||
match listener.accept().await {
|
||||
Ok((mut socket, addr)) => {
|
||||
println!("new client: {:?}", addr);
|
||||
socket.write_all(b"ciao").await?;
|
||||
socket.flush().await?;
|
||||
},
|
||||
Err(e) => println!("couldn't get client: {:?}", e),
|
||||
tokio::select! {
|
||||
bytes_read = reader.read_line(&mut line) => {
|
||||
if bytes_read.unwrap() == 0 {
|
||||
println!("connection closed");
|
||||
return;
|
||||
}
|
||||
tx.send(line.clone()).unwrap();
|
||||
},
|
||||
msg = rx.recv() => {
|
||||
write.write_all(format!("> {}", msg.unwrap()).as_bytes()).await.expect("failed to write data");
|
||||
line.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn spawn(mut stream: TcpStream) -> Result<(), anyhow::Error> {
|
||||
todo!()
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue