Created
August 15, 2016 20:05
-
-
Save Vultour/b313d045d4f7f3195886067c46886b39 to your computer and use it in GitHub Desktop.
TCP client in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate rand; | |
use std::io::prelude::*; | |
use std::thread; | |
use std::time::Duration; | |
use std::net::{TcpStream, Shutdown}; | |
use rand::Rng; | |
fn thread_exec(id: u32){ | |
let mut stream: TcpStream = TcpStream::connect("127.0.0.1:7777").unwrap(); | |
let iterations = rand::thread_rng().gen_range(5, 15); | |
let mut x = 0; | |
while x < iterations { | |
match stream.write(format!("Thread {}: {}\n", id, rand::thread_rng().gen_range(10000,100000)).as_bytes()){ | |
Ok(_) => { stream.flush().unwrap(); } | |
Err(e) => { println!("Error! - {}", e); } | |
} | |
thread::sleep(Duration::from_millis(rand::thread_rng().gen_range(150, 2000))); | |
x += 1; | |
} | |
stream.shutdown(Shutdown::Both).unwrap(); | |
println!("Client {} sent {} requests", id, iterations); | |
} | |
fn main(){ | |
let threads = rand::thread_rng().gen_range(5, 25); | |
let mut t = Vec::new(); | |
let mut x = 0; | |
while x < threads { | |
let y = x; | |
t.push( | |
thread::spawn(move || { | |
thread_exec(y); | |
}) | |
); | |
x += 1; | |
} | |
for thr in t{ thr.join().unwrap(); } | |
TcpStream::connect("127.0.0.1:7777").unwrap().write(String::from("quit\n").as_bytes()).unwrap(); | |
println!("Spawned {} clients", threads); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment