Rust server must save the updated value of variable

I need to realize TCP server, that stores a variable M. At the beginning, M = 1.
But, when the conntection set between server and client, and client sends another value of variable N, server must do next: M = M * N. And return that value to client.
And server must save that new value of variable M!
And, when next new client set connection, it will work with new value of variable.
Example:

  1. Server: M = 1; Client: N = 5; Server: M = 5;
  2. Server: A = 5; Client: N = 8; Server: M = 40;
  3. ...

This is my code of my server. And it works in that way:(not saving new value)
Example:

  1. Server: M = 1; Client: N = 5; Server: M = 5;
  2. Server: A = 1; Client: N = 8; Server: M = 8;
  3. ...
    Maybe should I do a gloval variable? Or something about it... Give me some advice. Thank you.
fn handle_client(mut stream: TcpStream, a:&mut i32) {
    let mut data = [0 as u8; 30]; // using 30 byte buffer
    
    while match stream.read(&mut data) {
    
        Ok(size) => {
           if size>0{
           
           let temp = str::from_utf8(&data[0..size]).unwrap().to_string();
                        
           let temp: i32  = temp.trim().parse().unwrap();                  
           
            *a = *a * temp;
                  
            let st = a.to_string();
            // String в u8
            let data = st.as_bytes();
            

            stream.write(&data).unwrap();
           }
            true
        },
        Err(_) => {
            println!("An error occurred, terminating connection with {}", stream.peer_addr().unwrap());
            stream.shutdown(Shutdown::Both).unwrap();
            false
        }
    } {}
}


fn main() {
    let listener = TcpListener::bind("0.0.0.0:7956").unwrap();
    
   let mut a: i32 = 1;
    // accept connections and process them, spawning a new thread for each one
    println!("Server listening on port 7956");
    println!("A = 1");
    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                println!("New connection: {}", stream.peer_addr().unwrap());
                thread::spawn(move|| {
                    // connection succeeded
                    handle_client(stream, &mut a)
                });
            }
            Err(e) => {
                println!("Error: {}", e);
                /* connection failed */
            }
        }
    }
    // close the socket server
    drop(listener);
}

The move keyword here causes the closure to make a copy of a, so each thread is mutating its own copy rather than the variable in main:

thread::spawn(move || {
    // connection succeeded
    handle_client(stream, &mut a)
});

If you want to update the value while it's shared across multiple threads, you can use a type like Arc<Mutex<T>>. Here's an example showing how to use it:

So, you're right! It was compiled! Thank you SO MUCH!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.