-
-
Save rust-play/05454e19d9a88208d7e4a467098f1855 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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
use ::{ | |
bytes::Bytes, | |
hdrhistogram::Histogram, | |
std::{ | |
convert::TryInto, | |
io::{self, | |
Read, Seek, SeekFrom, Write, | |
}, | |
mem, | |
net::{Shutdown, TcpStream}, | |
time::SystemTime, | |
}, | |
}; | |
struct LoopStruct { | |
tcp: TcpStream, | |
current_pointer: usize, | |
hist: Histogram<u64>, | |
} | |
fn main () | |
-> io::Result<()> | |
{ | |
let addr = String::from("127.0.0.1:8000"); | |
let loop_max = 100; | |
let xnow = SystemTime::now(); | |
// tcp and tcp2 are the connection pool | |
let tcp = TcpStream::connect(&addr); | |
let tcp2 = TcpStream::connect(&addr); | |
let mut flag = 1; | |
let mut tcp_timer_x = SystemTime::now(); | |
match tcp { | |
Err(e) => { | |
println!("Cannot connect {:?}", e); | |
}, | |
Ok(mut tcp) => { | |
let mut tcp = Some(tcp); | |
let mut tcp2 = Some(tcp2.unwrap()); | |
let current_pointer: usize = 0; | |
let hist: Histogram<u64> = Histogram::<u64>::new(2).unwrap(); | |
// below line doesn't doesn't work | |
// let tcp = tcp; // <----------------------------------------------------------------------------- | |
let mut t1 = LoopStruct { | |
tcp: tcp.take().unwrap(), | |
current_pointer, | |
hist, | |
}; | |
let mut loop_count = 1; | |
loop { | |
let mut i = 0; | |
loop { | |
let tcp_timer_y: u64 = | |
tcp_timer_x | |
.elapsed() | |
.unwrap() | |
.as_secs() | |
.try_into() | |
.unwrap() | |
; | |
let mut count = 1; | |
if tcp_timer_y > 5 { | |
println!("Switching now -------- $$$$$$$$$$$$$"); | |
t1.tcp.shutdown(Shutdown::Both); | |
println!("shutdown old conn -------- $$$$$$$$$$$$$"); | |
if flag == 1 { | |
//t1.tcp = *(&mut tcp2).unwrap(); | |
tcp = Some(mem::replace(&mut t1.tcp, tcp2.take().unwrap())); // <---------------------------------------------- | |
//should reconnect here | |
flag = 2; | |
} else { | |
tcp2 = Some(mem::replace(&mut t1.tcp, tcp.take().unwrap())); | |
flag = 1; | |
} | |
//t1.tcp = curr_tcp_conn; | |
count = count + 1; | |
println!("started new conn -------- $$$$$$$$$$$$$ {:?}", count); | |
tcp_timer_x = SystemTime::now(); | |
} | |
} | |
} | |
loop_count += 1; | |
if loop_count > loop_max { | |
let xnow1: u64 = | |
xnow.elapsed() | |
.unwrap() | |
.as_millis() | |
.try_into() | |
.unwrap() | |
; | |
t1 .tcp | |
.shutdown(Shutdown::Both) | |
.expect("shutdown call failed") | |
; | |
} | |
}, | |
} | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment