【发布时间】: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<std::net::UdpSocket, std::io::Error> 的名为 recv_from 的方法。
编辑: 这似乎是由于忘记处理从 UdpSocket::bind 返回的错误处理的结果。这在帖子中有更详细的讨论 How to do error handling in Rust and what are the common pitfalls? 如下所述。
因为我没有看到很多明确处理 net::UdpSocket 的问题或示例,所以基本保留这个问题
【问题讨论】:
-
这是非常基本的东西,我真的建议阅读the book,尤其是关于error handling的章节
-
我一直在阅读这本书,但是我对这些概念仍然很陌生(比如处理带有错误部分的退货),所以我在这里忽略了它。