From 843903400d2a70ef07b7df477716df164fd181aa Mon Sep 17 00:00:00 2001 From: szymon Date: Sat, 15 Aug 2026 16:09:08 +0200 Subject: [PATCH] feat: add sending to connection --- src/network/connection.rs | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/src/network/connection.rs b/src/network/connection.rs index 8d7500c..8f0e820 100644 --- a/src/network/connection.rs +++ b/src/network/connection.rs @@ -6,7 +6,7 @@ use log::{debug, error, warn}; use postcard::from_bytes; use tokio::{net::TcpStream, sync::mpsc::Sender}; -use tokio::io::AsyncReadExt; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; use crate::network::message::{Message, MessageLike}; @@ -23,6 +23,7 @@ where conn_type: ConnectionType, sender: Sender>, tcp: Option, + peer: Option, outbound_type: PhantomData, } @@ -39,6 +40,7 @@ where conn_type, sender, tcp: None, + peer: None, outbound_type: PhantomData, } } @@ -47,7 +49,10 @@ where match self.conn_type { ConnectionType::Server => { self.tcp = match TcpStream::connect(url).await { - Ok(conn) => Some(conn), + Ok(conn) => { + self.peer = Some(url); + Some(conn) + } Err(e) => { error!("Error while connecting to the server: {}", e); None @@ -61,7 +66,28 @@ where } pub async fn send(&mut self, msg: Message) { - todo!(); + let size = msg.size; + let content = msg.content; + + let Some(tcp) = &mut self.tcp else { + error!("Tcp connection is not established! Cannot send"); + return; + }; + + if let Err(e) = tcp.write_all(&size.to_be_bytes()).await { + error!("Error while sending header to: {:?}\n{}", self.peer, e); + return; + } + + let Ok(msg) = content.to_bits() else { + error!("Cannot change message into bytes while sending!"); + return; + }; + + if let Err(e) = tcp.write_all(&msg).await { + error!("Error while sending content to: {:?}\n{}", self.peer, e); + return; + }; } pub async fn start_listening(&mut self) { @@ -70,9 +96,8 @@ where if let Err(e) = result { error!( - "Error while reading data from connection with: {} {}. Connection is broken. Disconnecting...", - self.tcp.as_ref().unwrap().peer_addr().unwrap(), - e + "Error while reading data from connection with: {:?} {}. Connection is broken. Disconnecting...", + self.peer, e ); return; }