为什么在模块上实施actix websocket客户端时出现可见性错误

时间:2019-07-18 11:37:40

标签: rust rust-actix

我在以下位置改编了一个示例:actix 主要区别在于,在main.rs中,我已将WebsocketClient的声明移至ws_client.rs中。

main.rs

use actix::io::SinkWrite;
use actix::prelude::*;
use awc::Client;
use futures::{lazy, Future};
use std::io;
use std::thread;

mod ws_client;
mod command;

use crate::ws_client::WebsocketClient;
use crate::command::ClientCommand;

fn main() {
    let system = actix::System::new("test");

    Arbiter::spawn(lazy(|| {
        Client::new()
            .ws("http://127.0.0.1:8080/ws/")
            .connect()
            .map_err(|e| {
                println!("Error: {}", e);
            })
            .map(|(response, framed)| {
                println!("{:?}", response);
                let (sink, stream) = framed.split();
                let addr = WebsocketClient::create(|ctx| {
                    WebsocketClient::add_stream(stream, ctx);
                    WebsocketClient(SinkWrite::new(sink, ctx))
                });

                // start console loop
                thread::spawn(move || loop {
                    let mut cmd = String::new();
                    if io::stdin().read_line(&mut cmd).is_err() {
                        println!("error");
                        return;
                    }

                    cmd = cmd.trim().to_string();

                    if !cmd.is_empty() {
                        addr.do_send(ClientCommand(cmd));
                    }
                });
            })
    }));

    let _ = system.run();
}

command.rs

use actix::prelude::*;

#[derive(Message, Debug)]
pub struct ClientCommand(pub String);

ws_client.rs

#[macro_use]
use actix::io::SinkWrite;
use actix::prelude::*;
use actix_codec::{AsyncRead, AsyncWrite, Framed};
use awc::{
    error::WsProtocolError,
    ws::{Codec, Frame, Message},
};
use crate::command::ClientCommand;
use std::time::Duration;
use futures::{
    stream::{SplitSink},
};

pub struct WebsocketClient<T>(SinkWrite<SplitSink<Framed<T, Codec>>>)
where
    T: AsyncRead + AsyncWrite;

impl<T: 'static> Actor for WebsocketClient<T>
where
    T: AsyncRead + AsyncWrite,
{
    type Context = Context<Self>;

    fn started(&mut self, ctx: &mut Context<Self>) {
        // start heartbeats otherwise server will disconnect after 10 seconds
        self.hb(ctx)
    }

    fn stopped(&mut self, _: &mut Context<Self>) {
        println!("Disconnected");

        // Stop application on disconnect
        System::current().stop();
    }
}

impl<T: 'static> WebsocketClient<T>
where
    T: AsyncRead + AsyncWrite,
{
    fn hb(&self, ctx: &mut Context<Self>) {
        ctx.run_later(Duration::new(1, 0), |act, ctx| {
            act.0.write(Message::Ping(String::new())).unwrap();
            act.hb(ctx);

            // client should also check for a timeout here, similar to the
            // server code
        });
    }
}

/// Handle stdin commands
impl<T: 'static> Handler<ClientCommand> for WebsocketClient<T>
where
    T: AsyncRead + AsyncWrite,
{
    type Result = ();

    fn handle(&mut self, msg: ClientCommand, _ctx: &mut Context<Self>) {
        self.0.write(Message::Text(msg.0)).unwrap();
    }
}

/// Handle server websocket messages
impl<T: 'static> StreamHandler<Frame, WsProtocolError> for WebsocketClient<T>
where
    T: AsyncRead + AsyncWrite,
{
    fn handle(&mut self, msg: Frame, _ctx: &mut Context<Self>) {
        match msg {
            Frame::Text(txt) => println!("Server: {:?}", txt),
            _ => (),
        }
    }

    fn started(&mut self, _ctx: &mut Context<Self>) {
        println!("Connected");
    }

    fn finished(&mut self, ctx: &mut Context<Self>) {
        println!("Server disconnected");
        ctx.stop()
    }
}

impl<T: 'static> actix::io::WriteHandler<WsProtocolError> for WebsocketClient<T> where
    T: AsyncRead + AsyncWrite
{
}

整个链接与链接中的相同。没有新的代码。

但是编译器说:

error[E0423]: expected function, found struct `WebsocketClient`
  --> src/main.rs:29:21
   |
29 |                     WebsocketClient(SinkWrite::new(sink, ctx))
   |                     ^^^^^^^^^^^^^^^ constructor is not visible here due to private fields

error: aborting due to previous error

For more information about this error, try `rustc --explain E0423`.

Cargo.toml中的依赖项为:

actix = "0.8"
redis = "0.10"
futures = "0.1"
actix-codec = "0.1"
awc = "0.2"

0 个答案:

没有答案