mirror of
https://github.com/tokio-rs/tokio.git
synced 2026-08-07 00:00:09 +02:00
Related to #1318, Tokio APIs that are "less stable" are moved into a new `tokio-util` crate. This crate will mirror `tokio` and provide additional APIs that may require a greater rate of breaking changes. As examples require `tokio-util`, they are moved into a separate crate (`examples`). This has the added advantage of being able to avoid example only dependencies in the `tokio` crate.
80 lines
2.0 KiB
Rust
80 lines
2.0 KiB
Rust
use tokio::net::UdpSocket;
|
|
use tokio_util::codec::{Decoder, Encoder};
|
|
use tokio_util::udp::UdpFramed;
|
|
|
|
use bytes::{BufMut, BytesMut};
|
|
use futures_util::future::FutureExt;
|
|
use futures_util::sink::SinkExt;
|
|
use futures_util::stream::StreamExt;
|
|
use futures_util::try_future::try_join;
|
|
use std::io;
|
|
|
|
#[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);
|
|
|
|
let msg = b"4567".to_vec();
|
|
|
|
let send = a.send((msg.clone(), b_addr));
|
|
let recv = b.next().map(|e| e.unwrap());
|
|
let (_, received) = try_join(send, recv).await.unwrap();
|
|
|
|
let (data, addr) = received;
|
|
assert_eq!(msg, data);
|
|
assert_eq!(a_addr, addr);
|
|
|
|
a_soc = a.into_inner();
|
|
b_soc = b.into_inner();
|
|
}
|
|
|
|
// test sending & receiving an empty message
|
|
{
|
|
let mut a = UdpFramed::new(a_soc, ByteCodec);
|
|
let mut b = UdpFramed::new(b_soc, ByteCodec);
|
|
|
|
let msg = b"".to_vec();
|
|
|
|
let send = a.send((msg.clone(), b_addr));
|
|
let recv = b.next().map(|e| e.unwrap());
|
|
let (_, received) = try_join(send, recv).await.unwrap();
|
|
|
|
let (data, addr) = received;
|
|
assert_eq!(msg, data);
|
|
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()))
|
|
}
|
|
}
|
|
|
|
impl Encoder for ByteCodec {
|
|
type Item = Vec<u8>;
|
|
type Error = io::Error;
|
|
|
|
fn encode(&mut self, data: Vec<u8>, buf: &mut BytesMut) -> Result<(), io::Error> {
|
|
buf.reserve(data.len());
|
|
buf.put(data);
|
|
Ok(())
|
|
}
|
|
}
|