use connection_utils::codecs::GenericCodec; use tokio_util::codec::Framed; use futures::{StreamExt, SinkExt}; use tokio::{io::duplex, try_join}; use serde::{Serialize, Deserialize}; use cs_utils::{random_number, random_str, random_bool}; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] struct TestStruct { id: u16, name: String, is_flag: bool, } #[tokio::main] async fn main() { println!("\n🏷️ Generic codec example:"); let (stream1, stream2) = duplex(4096); let message = TestStruct { id: random_number(0..=u16::MAX), name: random_str(8), is_flag: random_bool(), }; let message1 = message.clone(); let message2 = message.clone(); try_join!( // Sender tokio::spawn(async move { let framed_stream = Framed::new( stream1, GenericCodec::::new(), ); let ( mut sink, _source, ) = framed_stream.split(); println!("> sending message: [{:?}]", &message1); sink .send(message1).await .expect("Cannot send the request."); }), // Receiver tokio::spawn(async move { let framed_stream = Framed::new( stream2, GenericCodec::::new(), ); let ( _sink, mut source, ) = framed_stream.split(); let received_message = source.next().await .expect("Cannot receive message.") .expect("Cannot receive message 2."); println!("< received message: [{:?}]", &received_message); assert_eq!( received_message, message2, ); }), ).unwrap(); }