Skip to content

Instantly share code, notes, and snippets.

@nixpulvis nixpulvis/process.rs
Last active Sep 28, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.