What have I done wrong?

I needed to convert the inner code with the loop into a sync function. Now the function blocks and the timeout does not seem to kill the loop which would kill the task and the function should return. Do you see anything here that would stop the function from returning?

fn new_listener(conn: std::sync::mpsc::Sender<DbMsg>, sockop: Arc<std::net::UdpSocket>){
    let sock = sockop.clone();
    tokio::spawn(
        tokio::time::timeout(tokio::time::Duration::from_secs(2),
        async move{
                let sock = sock.clone();
                loop{
                    let mut buf = [0u8; 1024];
                    let s = sock.clone();
                    let data = s.recv_from(&mut buf);
                    match data{
                        Ok((size,socket)) => {
                            match utils::dns_parse(buf){
                                Ok(msg)=>{
                                    let db = conn.clone();
                                    println!("{}",socket);
                                    let mut device = devices::Device::default();
                                    device.set_ip(Some(socket.ip()));
                                    device.set_verified(false);
                                    //db.send(message)
                                },
                                Err(e)=>{
                                    println!("DNS message Error: {}",e);
                                }
                            }
                        },
                        Err(e) => {
                            println!("{}", e)
                        }
                    }
                }
            }
            ));
}

A timeout cannot kill something that is blocking the thread. Both the channel and socket are blocking. Use the ones from Tokio instead.

4 Likes

Thanks! I'll give it a shot. That's a pretty big change.

It worked!

2 Likes

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.