gpt4 book ai didi

rust - Rust 中的 P2P 通信

转载 作者:行者123 更新时间:2023-11-29 08:35:30 25 4
gpt4 key购买 nike

我正在尝试编写一个 P2P 节点。一个节点包含一个对等点列表,打开一个监听端口让其他节点建立通信 channel ,同时主动尝试与其他一些被选中的节点建立连接。这种选择使得每对节点之间只有一个连接(未在以下代码段中实现)。

我正在尝试使用 futures 组合器通过 Tokio 实现这一目标。

main.rs

use failure::Error;

pub mod networking {
use failure::Error;

use std::net::SocketAddr;
use tokio::net::{TcpListener, TcpStream};
use tokio::prelude::*;

use crate::Config;
use futures::Future;

pub fn start(cfg: &Config) -> Result<(), Error> {
let myself = cfg.myself.parse::<SocketAddr>()?;
let others = cfg
.others
.iter()
.filter_map(|s| s.parse().ok())
.collect::<Vec<SocketAddr>>();

let server = TcpListener::bind(&myself)?
.incoming()
.for_each(|socket| {
println!("Got a socket: {:?}", socket);
future::ok(())
})
.map_err(|e| eprintln!("Error connecting: {:?}", e));

let client = TcpStream::connect(&others[0])
.map(|socket| {
println!("Got a socket: {:?}", socket);
})
.map_err(|e| eprintln!("Error connecting: {:?}", e));

let future = server.join(client);

tokio::run(future);

Ok(())
}
}

struct Config {
myself: String,
others: Vec<String>,
}

fn main() -> Result<(), Error> {
let config = Config {
myself: "127.0.0.1:2501".to_string(),
others: vec!["127.0.0.1:2502".to_string(), "127.0.0.1:2503".to_string()],
};
networking::start(&config)
}

( playground )

这不起作用:

error[E0271]: type mismatch resolving `<futures::future::join::Join<futures::future::map_err::MapErr<futures::stream::for_each::ForEach<tokio_tcp::incoming::Incoming, [closure@src/main.rs:23:23: 26:14], futures::future::result_::FutureResult<(), std::io::Error>>, [closure@src/main.rs:27:22: 27:64]>, futures::future::map_err::MapErr<futures::future::map::Map<tokio_tcp::stream::ConnectFuture, [closure@src/main.rs:30:18: 32:14]>, [closure@src/main.rs:33:22: 33:64]>> as futures::future::Future>::Item == ()`
--> src/main.rs:37:9
|
37 | tokio::run(future);
| ^^^^^^^^^^ expected tuple, found ()
|
= note: expected type `((), ())`
found type `()`
= note: required by `tokio::runtime::threadpool::run`

我明白编译器说的是什么,但我不知道我到底需要更正什么。我应该更正什么以使类型正确?

最佳答案

谢谢指教

let future = server.join(client);

必须更正为

let future = server.join(client).map(|_| ())

关于rust - Rust 中的 P2P 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58307723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com