Im trying to have a simple Struct in Rust to understand how to implement a Server that listening for clients, and have a method for sending data.
I couldn’t figure out how to use my struct in 2 different tasks.
I understand i might need to use Arc
for this, but cant understand how.
here is my code:
use std::time::Duration;
use tokio::time::sleep;
struct MyStruct {
data1: i32,
}
impl MyStruct {
pub async fn listen(&mut self) {
loop {
// demonstrating a long wait until a new client connected. using mut to save data regarding the clients.
println!("hi {}", self.data1);
sleep(Duration::from_secs(10000)).await;
self.data1 += 1;
}
}
pub async fn send_data_to_client(&self) {
// demonstrating sending data to client. no need for mut.
println!("hello");
}
}
#[tokio::main]
async fn main() {
println!("hi");
let mut s = MyStruct { data1: 0 };
let task1 = tokio::spawn(async move {
s.listen().await;
});
let task2 = tokio::spawn(async move {
s.send_data_to_client().await;
});
let _ = tokio::join!(task1, task2);
println!("All tasks completed.");
}