Debian Codegraph @

tests/many_connections.rs

raw symbols SCIP
1 //! Tests to ensure more than 32 connections can be polled at once.
2
3 // Doesn't work on OpenBSD.
4 #![cfg(not(target_os = "openbsd"))]
5
6 use std::io::{self, prelude::*};
7 use std::net::{TcpListener, TcpStream};
8 use std::time::Duration;
9
10 use polling::Events;
11
12 #[test]
13 fn many_connections() {
14 // Create 100 connections.
15 let mut connections = Vec::new();
16 for i in 0..100 {
17 let (reader, writer) = tcp_pair().unwrap();
18 connections.push((i, reader, writer));
19 }
20
21 // Create a poller and add all the connections.
22 let poller = polling::Poller::new().unwrap();
23
24 for (i, reader, _) in connections.iter() {
25 unsafe {
26 poller.add(reader, polling::Event::readable(*i)).unwrap();
27 }
28 }
29
30 let mut events = Events::new();
31 while !connections.is_empty() {
32 // Choose a random connection to write to.
33 let i = fastrand::usize(..connections.len());
34 let (id, mut reader, mut writer) = connections.remove(i);
35
36 // Write a byte to the connection.
37 writer.write_all(&[1]).unwrap();
38
39 // Wait for the connection to become readable.
40 poller
41 .wait(&mut events, Some(Duration::from_secs(10)))
42 .unwrap();
43
44 // Check that the connection is readable.
45 let current_events = events.iter().collect::<Vec<_>>();
46 assert_eq!(current_events.len(), 1, "events: {current_events:?}");
47 assert_eq!(
48 current_events[0].with_no_extra(),
49 polling::Event::readable(id)
50 );
51
52 // Read the byte from the connection.
53 let mut buf = [0];
54 reader.read_exact(&mut buf).unwrap();
55 assert_eq!(buf, [1]);
56 poller.delete(&reader).unwrap();
57 events.clear();
58 }
59 }
60
61 fn tcp_pair() -> io::Result<(TcpStream, TcpStream)> {
62 let listener = TcpListener::bind("127.0.0.1:0")?;
63 let a = TcpStream::connect(listener.local_addr()?)?;
64 let (b, _) = listener.accept()?;
65 Ok((a, b))
66 }