Rust中的套接字服务器未收到

时间:2019-06-15 20:23:59

标签: sockets rust udp netcat

server.rs:

use std::net::UdpSocket;

fn main() -> std::io::Result<()>{
  {
    let mut socket = UdpSocket::bind("127.0.0.1:3000")?;
    let mut buf = [0; 10];
    let (amt, src) = socket.recv_from(&mut buf)?;

    let buf = &mut buf[..amt];
    buf.reverse();
    socket.send_to(buf, &src)?;
  }
  Ok(())
}

strace ./server输出在此处停止:

<...>
socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, IPPROTO_IP) = 3
bind(3, {sa_family=AF_INET, sin_port=htons(3000), sin_addr=inet_addr("127.0.0.1")}, 16) = 0
recvfrom(3, 

在运行上述程序后尝试调用echo -n "qwerty" | netcat 127.0.0.1 3000并没有任何改变。

为什么?

1 个答案:

答案 0 :(得分:1)

默认情况下,netcat使用TCP。指示netcat使用UDP会产生预期的结果:

echo -n "qwerty" | netcat -u 127.0.0.1 3000

mcve输出:

/home/svetlin/.cargo/bin/cargo run --color=always --package mcve --bin mcve
    Finished dev [unoptimized + debuginfo] target(s) in 0.11s
     Running `target/debug/mcve`

Process finished with exit code 0