Created
May 6, 2024 14:31
-
-
Save moriarty99779/34d1f6e447a8e2029c96d5786c41c6d6 to your computer and use it in GitHub Desktop.
Rust Simple Echo Server on TCP Port 49152
This file contains hidden or 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::thread; | |
use std::net::{TcpListener, TcpStream, Shutdown}; | |
use std::io::{Read, Write}; | |
use std::process::Command; | |
fn handle_client(mut stream: TcpStream) { | |
let mut data = [0 as u8; 255]; | |
while match stream.read(&mut data) { | |
Ok(size) => { | |
stream.write(&data[0..size]).unwrap(); | |
true | |
}, | |
Err(_) => { | |
println!("Error! Terminating connection with {}", stream.peer_addr().unwrap()); | |
stream.shutdown(Shutdown::Both).unwrap(); | |
false | |
} | |
} {} | |
} | |
fn main() { | |
let listener = TcpListener::bind("0.0.0.0:49152").unwrap(); | |
// Accept connections and process them, spawning a new thread for each one | |
println!("Server listening on port 49152"); | |
for stream in listener.incoming() { | |
match stream { | |
Ok(stream) => { | |
println!("New connection: {}", stream.peer_addr().unwrap()); | |
thread::spawn(move|| { | |
// Successful connection | |
handle_client(stream) | |
}); | |
} | |
Err(e) => { | |
println!("Error: {}", e); | |
// Error making connection | |
} | |
} | |
} | |
// close the socket server | |
drop(listener); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment