【问题标题】:Rust std::net::UdpSocket no method named recv_fromRust std::net::UdpSocket 没有名为 recv_from 的方法
【发布时间】:2019-07-11 03:15:55
【问题描述】:

我正在使用simple example 创建一个 rust udp 客户端/服务器应用程序。但是当尝试使用 send_to 或 recv_from 方法时,我收到以下错误:

[E0599] 在当前范围内找不到类型 std::result::Result<std::net::UdpSocket, std::io::Error> 的名为 send_to 的方法。

我没有以任何方式更改 cargo.toml 文件,但我没想到我必须这样做,因为我使用的是 rust 版本 1.35.0 的标准库。

客户端和服务器都是使用 cargo new [filename] --bin 创建的,代码在 main.rs 中

客户

use std::net::{Ipv4Addr, SocketAddrV4, UdpSocket};
use std::io;

fn snd()  -> Result<(), io::Error> {
    // Define the local connection (to send the data from)
    let ip = Ipv4Addr::new(127, 0, 0, 1);
    let connection = SocketAddrV4::new(ip, 9992);

    // Bind the socket
    // let socket = try!(UdpSocket::bind(connection));
    let socket = UdpSocket::bind(connection);

    // Define the remote connection (to send the data to)
    let connection2 = SocketAddrV4::new(ip, 9991);

    // Send data via the socket
    let buf = &[0x01, 0x02, 0x03];
    socket.send_to(buf, &connection2);
    println!("{:?}", buf);

    Ok(())
}

fn main() {
    match snd() {
        Ok(()) => println!("All snd-ing went well"),
        Err(err) => println!("Error: {:?}", err),
    }
}

服务器

use std::net::{Ipv4Addr, SocketAddrV4, UdpSocket};
use std::io;

fn recv()  -> Result<(), io::Error> {
    // Define the local connection information
    let ip = Ipv4Addr::new(127, 0, 0, 1);
    let connection = SocketAddrV4::new(ip, 9991);

    // Bind the socket
    // let socket = try!(UdpSocket::bind(connection));
    let socket = UdpSocket::bind(connection);

    // Read from the socket
    let mut buf = [0; 10];
    // let (amt, src) = try!(socket.recv_from(&mut buf));
    let (amt, src) = socket.recv_from(&mut buf).expect("Didn't recieve data");

    // Print only the valid data (slice)
    println!("{:?}", &buf[0 .. amt]);

    Ok(())
}

fn main() {
    match recv() {
        Ok(()) => println!("All recv-ing went well"),
        Err(err) => println!("Error: {:?}", err),
    }
}


使用 cargo build 时,我在服务器端也收到以下错误。

[E0599] 在当前范围内找不到类型 std::result::Result&lt;std::net::UdpSocket, std::io::Error&gt; 的名为 recv_from 的方法。

编辑: 这似乎是由于忘记处理从 UdpSocket::bind 返回的错误处理的结果。这在帖子中有更详细的讨论 How to do error handling in Rust and what are the common pitfalls? 如下所述。

因为我没有看到很多明确处理 net::UdpSocket 的问题或示例,所以基本保留这个问题

【问题讨论】:

标签: rust udp


【解决方案1】:
let socket = UdpSocket::bind(connection);

此调用返回Result,它可以表示成功值或错误值。 unwrap() 强制它产生成功值(Ok 的内容)。如果出现错误,它也会恐慌(值为Err)。

let socket = UdpSocket::bind(connection).unwrap();

或者您也可以使用 expect ,它会在恐慌之前打印消息。

let socket = UdpSocket::bind(connection).expect("failed to bind host socket");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 2014-12-07
    • 2017-10-18
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    相关资源
    最近更新 更多