Skip to content

Instantly share code, notes, and snippets.

@PetrGlad
Last active December 10, 2018 11:10
Show Gist options
  • Save PetrGlad/b15b60d1cf4c35c3be428276f7accfbd to your computer and use it in GitHub Desktop.
Save PetrGlad/b15b60d1cf4c35c3be428276f7accfbd to your computer and use it in GitHub Desktop.
use std::net::TcpListener;
use std::net::UdpSocket;
use std::net::TcpStream;
use std::net::Shutdown;
use std::thread;
use std::io::BufReader;
use std::io::Write;
use std::io::BufRead;
fn session(mut ios: TcpStream) -> Result<(), std::io::Error> {
let peer_tag = ios.peer_addr()
.map(|addr| format!("{:?}", addr))
.unwrap_or("<unknown>".to_string());
ios.write(format!("HELLO {}\n", peer_tag).as_bytes())?;
let mut rdr = BufReader::new(ios.try_clone()?);
loop {
let mut message = String::new();
rdr.read_line(&mut message)?;
if message.len() == 0
|| message.to_lowercase().starts_with("bye") {
break;
}
println!("IN {}: {}", peer_tag, message);
ios.write(message.as_bytes())?;
}
ios.write(b"\nBYE\n")?;
ios.flush()?;
println!("BYE {}\n", peer_tag);
ios.shutdown(Shutdown::Both)?;
Ok(())
}
fn echo_server() {
let listener = TcpListener::bind("127.0.0.1:9123").unwrap();
println!("Listening on TCP port 9123, ready to accept");
for stream in listener.incoming() {
thread::spawn(|| {
session(stream.unwrap()).unwrap();
});
}
}
fn udp_server() {
let socket = UdpSocket::bind("127.0.0.1:9124").unwrap();
println!("Listening on UDP port 9124, ready to accept");
loop {
let mut buf = [0; 10];
let (cnt, src) = socket.recv_from(&mut buf).unwrap();
let msg = &mut buf[..cnt];
socket.send_to(format!("OK: {}\n", std::str::from_utf8(msg).unwrap()).as_bytes(), &src).unwrap();
}
}
fn main() {
thread::spawn(echo_server);
// thread::spawn(udp_server);
udp_server();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment