Last active
October 8, 2024 15:33
-
-
Save nixpulvis/cf41e07f7cf336fea373362bb15264fd to your computer and use it in GitHub Desktop.
Simple Rust Threaded TCP Client Server
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 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