1

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

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

我想隔离三个组件(websocket 发送/接收、蓝牙发送/接收、消息处理)。为了做到这一点,我想使用一个futures::sync::mpsc通道作为通道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

我试图用 a 来破解它.map_err,将错误转换为 a SendError,但SendError结构是私有的。

4

1 回答 1

2

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

stream
  .map_err(|err| eprintln!("stream error: {}", err))
  .forward(sink.sink_map_err(|err| eprintln!("sink error: {}", err)))
于 2019-06-30T02:47:22.950 回答