tokio-rs / doc-push

Tokio doc blitz effort - A concerted effort to improve Tokio's documentation.
MIT License
50 stars 7 forks source link

Forwarding over UDP sockets. #92

Closed alishir closed 5 years ago

alishir commented 5 years ago

I want to read data from udp socket and forward them to an other address, I read echo-udp example and create UdpFramed stream and sink, I can read continusely from stream but when I couldn't forward received data. Here is the code:

      let local_addr = "127.0.0.1:1234".parse().unwrap(); // listen on port 1234
      let sender_addr = "127.0.0.1:5234".parse().unwrap(); // listen on port 1234
      let remote_addr: SocketAddr = "127.0.0.1:6141".parse().unwrap(); // forward all received packets to 6141

      let listener = UdpSocket::bind(&local_addr).unwrap();
>>    let sender = UdpSocket::bind(&sender_addr).unwrap();

      let (_sink, src) = UdpFramed::new(listener, BytesCodec::new()).split();
      //let (s_sink, s_src) = UdpFramed::new(sender, BytesCodec::new()).split();

      let pr = src.for_each(move |(d, addr)| {
          println!("addr: {:}", addr);
>>        sender.send_dgram(d, &remote_addr);
          Ok(())
      }).map_err(|_| ());

In the code above I got cannot move out of captured outer variable in an FnMut closure error, and when I try following code I got cannot move out of borrowed content error.

      let local_addr = "127.0.0.1:1234".parse().unwrap(); // listen on port 1234
      let sender_addr = "127.0.0.1:5234".parse().unwrap(); // listen on port 1234
      let remote_addr: SocketAddr = "127.0.0.1:6141".parse().unwrap(); // forward all received packets to 6141

      let listener = UdpSocket::bind(&local_addr).unwrap();
      let sender = UdpSocket::bind(&sender_addr).unwrap();
      let sender = Arc::new(Mutex::new(sender));

      let (_sink, src) = UdpFramed::new(listener, BytesCodec::new()).split();
      //let (s_sink, s_src) = UdpFramed::new(sender, BytesCodec::new()).split();

      let pr = src.for_each(move |(d, addr)| {
          println!("addr: {:}", addr);
          let inner_sender = sender.clone();
>>        inner_sender.lock().unwrap().send_dgram(d, &remote_addr);
          Ok(())
      }).map_err(|_| ());
alishir commented 5 years ago

issue resolved by sink.send_all(src).