Skip to content

Instantly share code, notes, and snippets.

@Vultour
Created August 15, 2016 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vultour/b313d045d4f7f3195886067c46886b39 to your computer and use it in GitHub Desktop.
Save Vultour/b313d045d4f7f3195886067c46886b39 to your computer and use it in GitHub Desktop.
TCP client in Rust
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