gpt4 book ai didi

asynchronous - 将数据从流转发到 Tokio mpsc channel

转载 作者:行者123 更新时间:2023-11-29 08:33:07 28 4
gpt4 key购买 nike

我正在尝试创建一个异步 Rust 客户端,它在一端连接到 WebSocket 服务器,在另一端连接到蓝牙加密狗。在这两者之间会有一些过滤消息的逻辑。

我正在使用 rust-websocket用于 WebSocket 端的异步模块。

我想隔离三个组件(websocket 发送/接收、蓝牙发送/接收、消息处理)。为此,我想使用 futures::sync::mpsc channel 作为 Sink 以便将消息从 WebSocket 接收器传递到消息处理部分的循环。下面是我的代码的简化部分:

const CONNECTION: &'static str = "ws://127.0.0.1:4000/socket/websocket";

fn main() {
let mut core = Core::new().unwrap();

let (ws_send, ws_recv) = mpsc::channel(100);
let (ws_to_main, main_from_ws) = mpsc::channel(100);

let ws_future = ClientBuilder::new(CONNECTION)
.unwrap()
.add_protocol("rust-websocket")
.async_connect_insecure(&core.handle())
.and_then(|(duplex, _)| {
let (mut sink, stream) = duplex.split();

stream
.filter_map(|message| {
println!("Received Message: {:?}", message);
match message {
OwnedMessage::Close(e) => Some(OwnedMessage::Close(e)),
OwnedMessage::Ping(d) => Some(OwnedMessage::Pong(d)),
OwnedMessage::Text(msg) => Some(OwnedMessage::Text(msg)),
_ => None,
}
})
.forward(ws_to_main)
});
let result = core.run(ws_future).unwrap();
}

但是,当我运行这段代码时,我收到几条如下所示的错误消息:

error[E0277]: the trait bound `websocket::WebSocketError: std::convert::From<futures::sync::mpsc::SendError<websocket::OwnedMessage>>` is not satisfied
--> src/main.rs:103:22
|
103 | .forward(ws_to_main)
| ^^^^^^^ the trait `std::convert::From<futures::sync::mpsc::SendError<websocket::OwnedMessage>>` is not implemented for `websocket::WebSocketError`
|
= help: the following implementations were found:
<websocket::WebSocketError as std::convert::From<std::io::Error>>
<websocket::WebSocketError as std::convert::From<hyper::error::Error>>
<websocket::WebSocketError as std::convert::From<websocket::client::ParseError>>
<websocket::WebSocketError as std::convert::From<native_tls::Error>>
and 5 others

我尝试用 .map_err 将错误转换为 SendError,但 SendError 结构是私有(private)的。

最佳答案

一个快速的解决方案是将 steam 和 sink 的错误类型转换为相同的错误类型:

stream
.map_err(|err| eprintln!("stream error: {}", err))
.forward(sink.sink_map_err(|err| eprintln!("sink error: {}", err)))

关于asynchronous - 将数据从流转发到 Tokio mpsc channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45594885/

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