Skip to content

Commit

Permalink
Merge pull request #513 from stlankes/recvfrom
Browse files Browse the repository at this point in the history
add example to test the system calls `recv_from` and `sendto`
  • Loading branch information
mkroening authored Dec 18, 2023
2 parents d207a82 + 10f5ae4 commit e11dbee
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions examples/testudp/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,25 @@ fn main() {
loop {
// Receives a single datagram message on the socket.
// If `buf` is too small to hold, the message, it will be cut off.
println!("about to recv");
match socket.recv(&mut buf) {
Ok(received) => {
match socket.recv_from(&mut buf) {
Ok((received, addr)) => {
let msg = std::str::from_utf8(&buf[..received]).unwrap();
print!("received {}", msg);

// print msg without suffix `\n`
match msg.strip_suffix('\n') {
Some(striped_msg) => {
println!("received \"{}\" from {}", striped_msg, addr);
}
_ => {
println!("received \"{}\" from {}", msg, addr);
}
}

// send message back
socket
.send_to(msg.as_bytes(), addr)
.expect("Unable to send message back");

if msg.starts_with("exit") {
break;
}
Expand Down

0 comments on commit e11dbee

Please sign in to comment.