Skip to content

Instantly share code, notes, and snippets.

@gold24park
Created September 28, 2023 03:09
Show Gist options
  • Save gold24park/386955734b2feaf442c8915ae0485103 to your computer and use it in GitHub Desktop.
Save gold24park/386955734b2feaf442c8915ae0485103 to your computer and use it in GitHub Desktop.
rust udp client
use std::{
io::{stdin, BufRead},
net::UdpSocket,
str::from_utf8,
};
fn main() -> std::io::Result<()> {
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
println!("Usage: {} hostname", args[0]);
std::process::exit(1);
}
let hostname = &args[1];
let socket = UdpSocket::bind("0.0.0.0:0")?;
let peer = format!("{}:{}", hostname, 2000);
println!("host: {}", peer);
let stdin = stdin();
for line in stdin.lock().lines() {
let line = line.unwrap();
println!("Line read from stdin {}", line);
if &line == "BYE" {
break;
}
socket
.send_to(line.as_bytes(), peer.as_str())
.expect("Error on send");
let mut buf = [0; 65535];
let (read, _) = socket.recv_from(&mut buf)?;
let echo = from_utf8(&buf[..read]).unwrap();
println!("Echoed: {}", echo);
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment