Skip to content

Instantly share code, notes, and snippets.

@nixpulvis
Last active September 28, 2019 19:26
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 nixpulvis/cf41e07f7cf336fea373362bb15264fd to your computer and use it in GitHub Desktop.
Save nixpulvis/cf41e07f7cf336fea373362bb15264fd to your computer and use it in GitHub Desktop.
Simple Rust Threaded TCP Client Server
use std::io::prelude::*;
use std::thread;
use std::net::{TcpStream, TcpListener};
fn network_process() {
let listener = TcpListener::bind("127.0.0.1:1337").unwrap();
let mut handlers = Vec::new();
match listener.accept() {
Ok((mut socket, addr)) => {
println!("new client: {:?}", addr);
let handler = thread::spawn(move || {
// NOTE: You'll need to handle the fact that a single "message"
// may come over the wire in many pieces. Some data formats
// include a length up front that helps, others have specific
// EOF (end of "message") sequences. There are trade-offs.
let mut buf = [0; 10];
socket.read(&mut buf);
println!("read: {:?}", buf);
});
handlers.push(handler);
}
Err(e) => println!("couldn't get client: {:?}", e),
}
for handler in handlers {
handler.join();
}
}
fn client_process() {
let mut stream = TcpStream::connect("127.0.0.1:1337").unwrap();
stream.write(&[1]).unwrap();
}
fn main() {
let ps = {
let p1 = thread::spawn(client_process);
let p2 = thread::spawn(network_process);
vec![p1,p2]
// [p1,p2]
};
// Wait kindly for all parties to finish.
for process in ps {
process.join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment