Hi Team,
Need a help in below code:
we are trying to connect and shutdown the connection in separate thread but while passing tcp streams as mutable reference and address, and creating the connection, we are getting below error in tokio:spawn async line:
use of moved value: tcp1
value moved here, in previous iteration of looprustc(E0382)
cli.rs(12, 9): move occurs because tcp1
has type std::result::Result<std::net::TcpStream, std::io::Error>
, which does not implement the Copy
trait
cli.rs(47, 21): this reinitialization might get skipped
cli.rs(71, 37): value moved here, in previous iteration of loop
cli.rs(72, 62): use occurs due to use in generator
use std::net::{TcpStream};
use std::io::{self, Read, Write, Result};
use std::net::Shutdown;
use std::time::SystemTime;
use tokio::net::{TcpListener};
use tokio_stream::StreamExt;
use tokio_util::codec::LengthDelimitedCodec;
use std::{thread, time};
// use std::io;
fn main(){
let mut addr = String::from("127.0.0.1:8000");
let mut tcp1 = TcpStream::connect(&addr);
let mut tcp2 = TcpStream::connect(&addr);
let mut tcp_timer_x = SystemTime::now();
let mut tcp_flag = 1;
loop{
let tcp_timer_y :u64= tcp_timer_x.elapsed().unwrap().as_secs().try_into().unwrap();
if tcp_timer_y > 5{
println!("Switching now -------- $$$$$$$$$$$$$");
if tcp_flag == 1 {
if tcp2.is_ok(){
tcp_flag = 2;
println!("TCP2");
// t.shutdown(Shutdown::Both).expect("shutdown call failed");
// println!("TCP1 shutdown");
// t.write("hey this is tcp2".as_bytes()).unwrap();
}
else {
println!("Error in Tcp2");
}
}
if tcp_flag==2{
tcp1 = TcpStream::connect(&addr);
if tcp1.is_ok(){
tcp_flag = 2;
println!("TCP2");
}
else {
println!("Error in Tcp2");
}
}
tokio::spawn(async move {
if let Err(e) = shutandreconn(tcp_flag, &mut tcp1.unwrap(), &mut tcp2.unwrap(), &mut addr ).await {
println!("failed to process connection; error = {}", e);
}
});
}
tcp_timer_x = SystemTime::now();
}
let secs = time::Duration::from_secs(1);
thread::sleep(secs);
println!("Using tcp {:?}",tcp_flag);
}
async fn shutandreconn(mut tcpflag: i32, t1: &mut TcpStream , t2: &mut TcpStream, addrs: &mut std::string::String ) -> io::Result<()>
{
if(tcpflag==1){
*t2= TcpStream::connect(addrs.to_string()).unwrap();
t1.shutdown(Shutdown::Both).expect("shutdown call failed");
}
else{
*t1= TcpStream::connect(addrs.to_string()).unwrap();
t2.shutdown(Shutdown::Both).expect("shutdown call failed");
}
Ok(())
}
Please suggest, how to solve this error.