Skip to content

Instantly share code, notes, and snippets.

@hashmap
Created December 3, 2019 09:57
Show Gist options
  • Save hashmap/e13cd2222b8763e08c079601876b747b to your computer and use it in GitHub Desktop.
Save hashmap/e13cd2222b8763e08c079601876b747b to your computer and use it in GitHub Desktop.
use std::io::Read;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::time::Duration;
fn server() {
let listener = TcpListener::bind("0.0.0.0:3333").unwrap();
listener.set_nonblocking(true).expect("set nonblocking");
println!("Server listening on port 3333");
loop {
match listener.accept() {
Ok((mut stream, _)) => {
println!("New connection");
//stream.set_nonblocking(false).expect("nonblock");
stream
.set_read_timeout(Some(Duration::from_secs(10)))
.expect("set timeout");
let mut data = [0 as u8; 2];
match stream.read_exact(&mut data) {
Ok(_) => println!("Got message!"),
Err(e) => println!("Failed to receive data: {:?}", e),
}
}
Err(_e) => {
//println!("Error: {:?}", e);
thread::sleep(Duration::from_secs(1));
}
}
}
}
fn client() {
match TcpStream::connect("localhost:3333") {
Ok(_) => {
println!("Successfully connected to server");
thread::sleep(Duration::from_secs(20));
}
Err(e) => {
println!("Failed to connect: {}", e);
}
}
}
fn main() {
let srv = thread::spawn(server);
thread::sleep(Duration::from_secs(1));
let _ = thread::spawn(client);
srv.join().expect("join");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment