Skip to content

Instantly share code, notes, and snippets.

@nixpulvis nixpulvis/
Last active Sep 28, 2019

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("").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]; buf);
println!("read: {:?}", buf);
Err(e) => println!("couldn't get client: {:?}", e),
for handler in handlers {
fn client_process() {
let mut stream = TcpStream::connect("").unwrap();
fn main() {
let ps = {
let p1 = thread::spawn(client_process);
let p2 = thread::spawn(network_process);
// [p1,p2]
// Wait kindly for all parties to finish.
for process in ps {
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.