Files
tokio/tests/udp.rs
T

66 lines
1.5 KiB
Rust
Raw Normal View History

2016-08-02 23:56:01 -07:00
extern crate futures;
2016-09-01 16:42:48 -07:00
#[macro_use]
2016-08-26 14:30:46 -07:00
extern crate tokio_core;
2016-08-02 23:56:01 -07:00
2016-08-17 09:29:05 -07:00
use std::io;
use std::net::SocketAddr;
use futures::{Future, Poll};
2016-09-02 11:07:52 -07:00
use tokio_core::net::UdpSocket;
use tokio_core::reactor::Core;
2016-08-02 23:56:01 -07:00
macro_rules! t {
($e:expr) => (match $e {
Ok(e) => e,
Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
})
}
#[test]
fn send_messages() {
2016-09-02 11:07:52 -07:00
let mut l = t!(Core::new());
2016-09-07 16:11:19 -07:00
let a = t!(UdpSocket::bind(&t!("127.0.0.1:0".parse()), &l.handle()));
let b = t!(UdpSocket::bind(&t!("127.0.0.1:0".parse()), &l.handle()));
2016-08-02 23:56:01 -07:00
let a_addr = t!(a.local_addr());
let b_addr = t!(b.local_addr());
2016-08-17 09:29:05 -07:00
let send = SendMessage { socket: a, addr: b_addr };
let recv = RecvMessage { socket: b, expected_addr: a_addr };
t!(l.run(send.join(recv)));
}
struct SendMessage {
socket: UdpSocket,
addr: SocketAddr,
}
2016-08-02 23:56:01 -07:00
2016-08-17 09:29:05 -07:00
impl Future for SendMessage {
type Item = ();
type Error = io::Error;
2016-08-02 23:56:01 -07:00
2016-08-17 09:29:05 -07:00
fn poll(&mut self) -> Poll<(), io::Error> {
2016-09-01 16:42:48 -07:00
let n = try_nb!(self.socket.send_to(b"1234", &self.addr));
assert_eq!(n, 4);
Ok(().into())
2016-08-17 09:29:05 -07:00
}
}
struct RecvMessage {
socket: UdpSocket,
expected_addr: SocketAddr,
}
2016-08-02 23:56:01 -07:00
2016-08-17 09:29:05 -07:00
impl Future for RecvMessage {
type Item = ();
type Error = io::Error;
2016-08-02 23:56:01 -07:00
2016-08-17 09:29:05 -07:00
fn poll(&mut self) -> Poll<(), io::Error> {
let mut buf = [0; 32];
2016-09-01 16:42:48 -07:00
let (n, addr) = try_nb!(self.socket.recv_from(&mut buf));
assert_eq!(n, 4);
assert_eq!(&buf[..4], b"1234");
assert_eq!(addr, self.expected_addr);
Ok(().into())
2016-08-17 09:29:05 -07:00
}
2016-08-02 23:56:01 -07:00
}