Import the actix-websocket example client code.

This is just to checkpoint this work. I think I'll be refactoring the eventbus
quite a bit to make sure that each eventbus client doesn't need to do too much
custom actix work
This commit is contained in:
R Tyler Croy 2019-12-30 08:03:07 -08:00
parent 74feb6172a
commit 950fec403a
No known key found for this signature in database
GPG Key ID: E5C92681BEF6CEA2
5 changed files with 179 additions and 9 deletions

24
Cargo.lock generated
View File

@ -334,10 +334,6 @@ dependencies = [
"winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "auctioneer"
version = "0.1.0"
[[package]]
name = "autocfg"
version = "0.1.7"
@ -1095,6 +1091,26 @@ name = "opaque-debug"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "otto-auctioneer"
version = "0.1.0"
dependencies = [
"actix 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
"actix-codec 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
"actix-rt 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"actix-web 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"actix-web-actors 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"awc 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
"bytes 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)",
"config 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)",
"futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
"otto-eventbus 0.1.0",
"pretty_env_logger 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 1.0.44 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "otto-eventbus"
version = "0.1.0"

1
auctioneer/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
target/

View File

@ -1,9 +1,34 @@
[package]
name = "auctioneer"
name = "otto-auctioneer"
version = "0.1.0"
authors = ["R. Tyler Croy <rtyler@brokenco.de>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix = "~0.9.0"
# Grabbing an alpha version with async/await support.
actix-web = "~2.0.0"
# This crate provides the websocket support which we will rely on for all
# clients
actix-web-actors = "~2.0.0"
actix-codec = "0.2.0"
awc = "1.0.1"
actix-rt = "~1.0.0"
futures = "0.3.1"
bytes = "0.5.3"
# Handling command line options
#clap = { version = "~2.33.0", features = ["yaml"] }
# Handling configuration overlays
config = { version = "~0.10.1", features = ["yaml"] }
# Logging
log = "~0.4.8"
pretty_env_logger = "~0.3.1"
# Adding the "rc" feature so we can serialize/deserialize Arc<T> and Rc<T>
serde = { version = "~1.0.103", features = ["rc"] }
serde_json = "~1.0.0"
otto-eventbus = { path = "../eventbus" }

View File

@ -1,3 +1,130 @@
fn main() {
println!("Hello, world!");
extern crate pretty_env_logger;
use std::time::Duration;
use std::{io, thread};
use actix::io::SinkWrite;
use actix::*;
use actix_codec::{AsyncRead, AsyncWrite, Framed};
use awc::{
error::WsProtocolError,
ws::{Codec, Frame, Message},
Client,
};
use bytes::Bytes;
use futures::stream::{SplitSink, StreamExt};
use otto_eventbus::Command;
#[actix_rt::main]
async fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info");
pretty_env_logger::init();
let (response, framed) = Client::new()
.ws("http://127.0.0.1:8000/ws/")
.connect()
.await
.map_err(|e| {
println!("Error: {}", e);
})
.unwrap();
println!("{:?}", response);
let (sink, stream) = framed.split();
let addr = ChatClient::create(|ctx| {
ChatClient::add_stream(stream, ctx);
ChatClient(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;
}
addr.do_send(ClientCommand(cmd));
});
}
struct ChatClient<T>(SinkWrite<Message, SplitSink<Framed<T, Codec>, Message>>)
where
T: AsyncRead + AsyncWrite;
#[derive(Message)]
#[rtype(result = "()")]
struct ClientCommand(String);
impl<T: 'static> Actor for ChatClient<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> ChatClient<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(Bytes::from_static(b""))).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 ChatClient<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<Result<Frame, WsProtocolError>> for ChatClient<T>
where
T: AsyncRead + AsyncWrite,
{
fn handle(&mut self, msg: Result<Frame, WsProtocolError>, _: &mut Context<Self>) {
if let Ok(Frame::Text(txt)) = msg {
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 ChatClient<T> where
T: AsyncRead + AsyncWrite
{
}

View File

@ -21,6 +21,7 @@ chrono = "~0.4.10"
# Handling command line options
#clap = { version = "~2.33.0", features = ["yaml"] }
# Handling configuration overlays
config = { version = "~0.10.1", features = ["yaml"] }
# Logging