]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/tcp-stress.rs
rollup merge of #20482: kmcallister/macro-reform
[rust.git] / src / test / run-pass / tcp-stress.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // ignore-linux see joyent/libuv#1189
12 // ignore-android needs extra network permissions
13 // exec-env:RUST_LOG=debug
14
15 #[macro_use]
16 extern crate log;
17 extern crate libc;
18
19 use std::sync::mpsc::channel;
20 use std::io::net::tcp::{TcpListener, TcpStream};
21 use std::io::{Acceptor, Listener};
22 use std::thread::{Builder, Thread};
23 use std::time::Duration;
24
25 fn main() {
26     // This test has a chance to time out, try to not let it time out
27     Thread::spawn(move|| -> () {
28         use std::io::timer;
29         timer::sleep(Duration::milliseconds(30 * 1000));
30         println!("timed out!");
31         unsafe { libc::exit(1) }
32     }).detach();
33
34     let (tx, rx) = channel();
35     Thread::spawn(move || -> () {
36         let mut listener = TcpListener::bind("127.0.0.1:0").unwrap();
37         tx.send(listener.socket_name().unwrap()).unwrap();
38         let mut acceptor = listener.listen();
39         loop {
40             let mut stream = match acceptor.accept() {
41                 Ok(stream) => stream,
42                 Err(error) => {
43                     debug!("accept panicked: {}", error);
44                     continue;
45                 }
46             };
47             stream.read_byte();
48             stream.write(&[2]);
49         }
50     }).detach();
51     let addr = rx.recv().unwrap();
52
53     let (tx, rx) = channel();
54     for _ in range(0u, 1000) {
55         let tx = tx.clone();
56         Builder::new().stack_size(64 * 1024).spawn(move|| {
57             match TcpStream::connect(addr) {
58                 Ok(stream) => {
59                     let mut stream = stream;
60                     stream.write(&[1]);
61                     let mut buf = [0];
62                     stream.read(&mut buf);
63                 },
64                 Err(e) => debug!("{}", e)
65             }
66             tx.send(()).unwrap();
67         }).detach();
68     }
69
70     // Wait for all clients to exit, but don't wait for the server to exit. The
71     // server just runs infinitely.
72     drop(tx);
73     for _ in range(0u, 1000) {
74         rx.recv().unwrap();
75     }
76     unsafe { libc::exit(0) }
77 }