1
0
mirror of https://github.com/actix/examples synced 2024-12-18 00:13:57 +01:00

simplify websokcet client example with BoxedSocket (#166)

* fix tokio timer error for websocket client

* simplify webscoket client
This commit is contained in:
Guoli Lyu 2020-01-06 12:59:45 +08:00 committed by Yuki Okushi
parent fed19e37b9
commit b91f0c9db2

View File

@ -4,59 +4,58 @@ use std::{io, thread};
use actix::io::SinkWrite; use actix::io::SinkWrite;
use actix::*; use actix::*;
use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_codec::Framed;
use awc::{ use awc::{
error::WsProtocolError, error::WsProtocolError,
ws::{Codec, Frame, Message}, ws::{Codec, Frame, Message},
Client, BoxedSocket, Client,
}; };
use bytes::Bytes; use bytes::Bytes;
use futures::stream::{SplitSink, StreamExt}; use futures::stream::{SplitSink, StreamExt};
#[actix_rt::main] fn main() {
async fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info"); ::std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init(); env_logger::init();
let (response, framed) = Client::new() let sys = System::new("websocket-client");
.ws("http://127.0.0.1:8080/ws/")
.connect()
.await
.map_err(|e| {
println!("Error: {}", e);
})
.unwrap();
println!("{:?}", response); Arbiter::spawn(async {
let (sink, stream) = framed.split(); let (response, framed) = Client::new()
let addr = ChatClient::create(|ctx| { .ws("http://127.0.0.1:8080/ws/")
ChatClient::add_stream(stream, ctx); .connect()
ChatClient(SinkWrite::new(sink, ctx)) .await
}); .map_err(|e| {
println!("Error: {}", e);
})
.unwrap();
// start console loop println!("{:?}", response);
thread::spawn(move || loop { let (sink, stream) = framed.split();
let mut cmd = String::new(); let addr = ChatClient::create(|ctx| {
if io::stdin().read_line(&mut cmd).is_err() { ChatClient::add_stream(stream, ctx);
println!("error"); ChatClient(SinkWrite::new(sink, ctx))
return; });
}
addr.do_send(ClientCommand(cmd)); // start console loop
thread::spawn(move || loop {
let mut cmd = String::new();
if io::stdin().read_line(&mut cmd).is_err() {
println!("error");
return;
}
addr.do_send(ClientCommand(cmd));
});
}); });
sys.run().unwrap();
} }
struct ChatClient<T>(SinkWrite<Message, SplitSink<Framed<T, Codec>, Message>>) struct ChatClient(SinkWrite<Message, SplitSink<Framed<BoxedSocket, Codec>, Message>>);
where
T: AsyncRead + AsyncWrite;
#[derive(Message)] #[derive(Message)]
#[rtype(result = "()")] #[rtype(result = "()")]
struct ClientCommand(String); struct ClientCommand(String);
impl<T: 'static> Actor for ChatClient<T> impl Actor for ChatClient {
where
T: AsyncRead + AsyncWrite,
{
type Context = Context<Self>; type Context = Context<Self>;
fn started(&mut self, ctx: &mut Context<Self>) { fn started(&mut self, ctx: &mut Context<Self>) {
@ -72,10 +71,7 @@ where
} }
} }
impl<T: 'static> ChatClient<T> impl ChatClient {
where
T: AsyncRead + AsyncWrite,
{
fn hb(&self, ctx: &mut Context<Self>) { fn hb(&self, ctx: &mut Context<Self>) {
ctx.run_later(Duration::new(1, 0), |act, ctx| { ctx.run_later(Duration::new(1, 0), |act, ctx| {
act.0.write(Message::Ping(Bytes::from_static(b""))).unwrap(); act.0.write(Message::Ping(Bytes::from_static(b""))).unwrap();
@ -88,10 +84,7 @@ where
} }
/// Handle stdin commands /// Handle stdin commands
impl<T: 'static> Handler<ClientCommand> for ChatClient<T> impl Handler<ClientCommand> for ChatClient {
where
T: AsyncRead + AsyncWrite,
{
type Result = (); type Result = ();
fn handle(&mut self, msg: ClientCommand, _ctx: &mut Context<Self>) { fn handle(&mut self, msg: ClientCommand, _ctx: &mut Context<Self>) {
@ -100,10 +93,7 @@ where
} }
/// Handle server websocket messages /// Handle server websocket messages
impl<T: 'static> StreamHandler<Result<Frame, WsProtocolError>> for ChatClient<T> impl StreamHandler<Result<Frame, WsProtocolError>> for ChatClient {
where
T: AsyncRead + AsyncWrite,
{
fn handle(&mut self, msg: Result<Frame, WsProtocolError>, _: &mut Context<Self>) { fn handle(&mut self, msg: Result<Frame, WsProtocolError>, _: &mut Context<Self>) {
if let Ok(Frame::Text(txt)) = msg { if let Ok(Frame::Text(txt)) = msg {
println!("Server: {:?}", txt) println!("Server: {:?}", txt)
@ -120,7 +110,4 @@ where
} }
} }
impl<T: 'static> actix::io::WriteHandler<WsProtocolError> for ChatClient<T> where impl actix::io::WriteHandler<WsProtocolError> for ChatClient {}
T: AsyncRead + AsyncWrite
{
}