Skip to content

Instantly share code, notes, and snippets.

@4ydx
Forked from fortruce/main.rs
Created June 18, 2023 01:05
Show Gist options
  • Save 4ydx/835afca0c7ffe7a43d8f8d3c0b38c198 to your computer and use it in GitHub Desktop.
Save 4ydx/835afca0c7ffe7a43d8f8d3c0b38c198 to your computer and use it in GitHub Desktop.
Simple TCP Echo Server in Rust
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::io::Read;
use std::io::Write;
fn handle_client(mut stream: TcpStream) {
// read 20 bytes at a time from stream echoing back to stream
loop {
let mut read = [0; 1028];
match stream.read(&mut read) {
Ok(n) => {
if n == 0 {
// connection was closed
break;
}
stream.write(&read[0..n]).unwrap();
}
Err(err) => {
panic!(err);
}
}
}
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move || {
handle_client(stream);
});
}
Err(_) => {
println!("Error");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment