summaryrefslogtreecommitdiffstats
path: root/tests/udp.rs
blob: 8f1ba5a9b7f4141a53544cbbb33199d6a14b9c88 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
extern crate futures;
extern crate futures_mio;

use std::io;
use std::net::SocketAddr;

use futures::{Future, Poll};
use futures_mio::UdpSocket;

macro_rules! t {
    ($e:expr) => (match $e {
        Ok(e) => e,
        Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
    })
}

#[test]
fn send_messages() {
    let mut l = t!(futures_mio::Loop::new());
    let a = l.handle().udp_bind(&"127.0.0.1:0".parse().unwrap());
    let b = l.handle().udp_bind(&"127.0.0.1:0".parse().unwrap());
    let (a, b) = t!(l.run(a.join(b)));
    let a_addr = t!(a.local_addr());
    let b_addr = t!(b.local_addr());

    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,
}

impl Future for SendMessage {
    type Item = ();
    type Error = io::Error;

    fn poll(&mut self) -> Poll<(), io::Error> {
        match self.socket.send_to(b"1234", &self.addr) {
            Ok(4) => Poll::Ok(()),
            Ok(n) => panic!("didn't send 4 bytes: {}", n),
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Poll::NotReady,
            Err(e) => Poll::Err(e),
        }
    }
}

struct RecvMessage {
    socket: UdpSocket,
    expected_addr: SocketAddr,
}

impl Future for RecvMessage {
    type Item = ();
    type Error = io::Error;

    fn poll(&mut self) -> Poll<(), io::Error> {
        let mut buf = [0; 32];
        match self.socket.recv_from(&mut buf) {
            Ok((4, addr)) => {
                assert_eq!(&buf[..4], b"1234");
                assert_eq!(addr, self.expected_addr);
                Poll::Ok(())
            }
            Ok((n, _)) => panic!("didn't read 4 bytes: {}", n),
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Poll::NotReady,
            Err(e) => Poll::Err(e),
        }
    }
}