-
-
Save 4ydx/835afca0c7ffe7a43d8f8d3c0b38c198 to your computer and use it in GitHub Desktop.
Simple TCP Echo Server in Rust
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::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