Files
tokio/tokio-util/tests/udp.rs
T

80 lines
2.1 KiB
Rust
Raw Normal View History

2019-12-18 22:57:22 +03:00
use tokio::{net::UdpSocket, stream::StreamExt};
2019-10-22 10:13:49 -07:00
use tokio_util::codec::{Decoder, Encoder};
use tokio_util::udp::UdpFramed;
use bytes::{BufMut, BytesMut};
use futures::future::try_join;
use futures::future::FutureExt;
use futures::sink::SinkExt;
2019-10-22 10:13:49 -07:00
use std::io;
2020-03-04 15:54:41 -05:00
#[cfg_attr(any(target_os = "macos", target_os = "ios"), allow(unused_assignments))]
2019-10-22 10:13:49 -07:00
#[tokio::test]
async fn send_framed() -> std::io::Result<()> {
let mut a_soc = UdpSocket::bind("127.0.0.1:0").await?;
let mut b_soc = UdpSocket::bind("127.0.0.1:0").await?;
let a_addr = a_soc.local_addr()?;
let b_addr = b_soc.local_addr()?;
// test sending & receiving bytes
{
let mut a = UdpFramed::new(a_soc, ByteCodec);
let mut b = UdpFramed::new(b_soc, ByteCodec);
2020-03-04 15:54:41 -05:00
let msg = b"4567";
2019-10-22 10:13:49 -07:00
2020-03-04 15:54:41 -05:00
let send = a.send((msg, b_addr));
2019-10-22 10:13:49 -07:00
let recv = b.next().map(|e| e.unwrap());
let (_, received) = try_join(send, recv).await.unwrap();
let (data, addr) = received;
2020-03-04 15:54:41 -05:00
assert_eq!(msg, &*data);
2019-10-22 10:13:49 -07:00
assert_eq!(a_addr, addr);
a_soc = a.into_inner();
b_soc = b.into_inner();
}
2020-03-04 15:54:41 -05:00
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
2019-10-22 10:13:49 -07:00
// test sending & receiving an empty message
{
let mut a = UdpFramed::new(a_soc, ByteCodec);
let mut b = UdpFramed::new(b_soc, ByteCodec);
2020-03-04 15:54:41 -05:00
let msg = b"";
2019-10-22 10:13:49 -07:00
2020-03-04 15:54:41 -05:00
let send = a.send((msg, b_addr));
2019-10-22 10:13:49 -07:00
let recv = b.next().map(|e| e.unwrap());
let (_, received) = try_join(send, recv).await.unwrap();
let (data, addr) = received;
2020-03-04 15:54:41 -05:00
assert_eq!(msg, &*data);
2019-10-22 10:13:49 -07:00
assert_eq!(a_addr, addr);
}
Ok(())
}
pub struct ByteCodec;
impl Decoder for ByteCodec {
type Item = Vec<u8>;
type Error = io::Error;
fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Vec<u8>>, io::Error> {
let len = buf.len();
Ok(Some(buf.split_to(len).to_vec()))
}
}
2020-03-04 15:54:41 -05:00
impl Encoder<&[u8]> for ByteCodec {
2019-10-22 10:13:49 -07:00
type Error = io::Error;
2020-03-04 15:54:41 -05:00
fn encode(&mut self, data: &[u8], buf: &mut BytesMut) -> Result<(), io::Error> {
2019-10-22 10:13:49 -07:00
buf.reserve(data.len());
2020-03-04 15:54:41 -05:00
buf.put_slice(data);
2019-10-22 10:13:49 -07:00
Ok(())
}
}