Sorry for my pool English first!
I have a scene :I need to use tokio tcpstream keepalive conncet to a server .when disconncet or err,I need to reconnect to the server again after every 30 secs. other I rcv msg from Upper using mpsc channel ,then do some opr ,and then send the result to server.At the same time I rcv msg from server then do some opr ,then send to upper . I have write code using tokio loop select!but I can not solve the reconnect promblem. Awesome rust boss help me!
impl ComOpr_232 {
pub async fn run(&mut self, shutdown_complete_tx_comx: mpsc::Sender<()>) {
let mut interval = time::interval(Duration::from_millis(160));
let mut interval_3s = time::interval(Duration::from_secs(3));
let mut interval_60s = time::interval(Duration::from_secs(60));
//12 sec se
let mut com_stat_send_index: usize = 0;
let mut buf: [u8; SERIBUFSIZE_NORMAL] = [0; SERIBUFSIZE_NORMAL];
loop {
tokio::select! {
// If you run this example without `biased;`, the polling order is
// psuedo-random, and the assertions on the value of count will
// (probably) fail.
biased;
_ = self.notify_shutdown_com_x.recv() => {
return ;
}
// some regular task
_= interval_3s.tick()=>{
if com_stat_send_index%4==0{
let mut bx_com_info=Box::new(comdata::ComStat::default());
*bx_com_info=self.run_data.comstat.clone();
self.to_main_x_tx.try_send( glb::ExData::ComSelfInfo(self.com_index,bx_com_info)) ;
}
}
// recv upper msg then send to server
Some(out_info)=self.to_com_5_rx.recv() =>{
}
// regular send read cmd to server
_= interval.tick() =>{
}
//wait for server send back the send back to upper
res = self.port.next() =>{
if res.is_some() {
//println!("get a frame back");
if let Some(Ok(recv_bytes))=res{
}
}else{
println!("rs232 closed should not happen");
}
}
}
}
}
}
for add the reconnect func, someone other told me use like this
#[pin_project]
struct MaybeTcpStream(#[pin] Option<TcpStream>);
impl AsyncRead for MaybeTcpStream {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context,
buf: &mut ReadBuf,
) -> Poll<std::io::Result<()>> {
let stream = self.project().0.as_pin_mut();
match stream {
Some(stream) => stream.poll_read(cx, buf),
None => Poll::Pending,
}
}
}
but use the wrapper ,when reconnect ,
**sorry for my pool English **
Thank you for reading .Wish you all the best .