first client commit

This commit is contained in:
Andrea Moro 2024-11-25 15:45:26 +01:00
commit f54ec8fe1d
4 changed files with 1174 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/target
.idea

1094
Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

13
Cargo.toml Normal file
View file

@ -0,0 +1,13 @@
[package]
name = "chatclient"
version = "0.1.0"
edition = "2021"
[dependencies]
colog = "1.3.0"
crossterm = "0.28.1"
futures = "0.3.31"
log = "0.4.22"
ratatui = "0.29.0"
tokio = { version = "1.41.1", features = ["full"] }
tokio-util = { version = "0.7.12", features = ["codec"] }

65
src/main.rs Normal file
View file

@ -0,0 +1,65 @@
use futures::{SinkExt, StreamExt};
use log::info;
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use tokio_util::codec::{Framed, LinesCodec};
#[tokio::main]
async fn main() {
colog::init();
info!("Client");
info!("Enter Server Address");
let addr: String = read_string();
info!("Server address: {}", &addr);
let stream = TcpStream::connect(addr)
.await
.expect("Could not connect to server");
info!("Connected to server");
let (tx, mut rx) = mpsc::channel::<String>(32);
let mut frame = Framed::new(stream, LinesCodec::new());
// Spawn a single task to handle both sending and receiving
let network_task = tokio::spawn(async move {
loop {
tokio::select! {
Some(Ok(line)) = frame.next() => {
info!("Received: {}", line);
}
Some(message) = rx.recv() => {
if let Err(e) = frame.send(message).await {
info!("Failed to send message: {}", e);
break;
}
}
else => break,
}
}
});
// Main loop for reading user input
loop {
info!("Enter message to send:");
let message = read_string();
if let Err(e) = tx.send(message).await {
info!("Failed to send to channel: {}", e);
break;
}
}
// Wait for the network and heartbeat tasks to complete
if let Err(e) = network_task.await {
info!("Network task failed: {}", e);
}
}
fn read_string() -> String {
let mut input = String::new();
std::io::stdin()
.read_line(&mut input)
.expect("can not read user input");
input.trim().to_string()
}