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:
- Server: M = 1; Client: N = 5; Server: M = 5;
- Server: A = 5; Client: N = 8; Server: M = 40;
- ...
This is my code of my server. And it works in that way:(not saving new value)
Example:
- Server: M = 1; Client: N = 5; Server: M = 5;
- Server: A = 1; Client: N = 8; Server: M = 8;
- ...
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);
}