//! Simple websocket client.
use std::time::Duration;
use actix::io::SinkWrite;
use actix::*;
use actix_codec::Framed;
use awc::{
error::WsProtocolError,
ws::{Codec, Frame, Message},
BoxedSocket, Client,
};
use bytes::Bytes;
use futures::stream::{SplitSink, StreamExt};
use chrono::prelude::*;
struct WebsocketClient {
sink_write: SinkWrite<Message, SplitSink<Framed<BoxedSocket, Codec>, Message>>,
}
impl Actor for WebsocketClient {
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");
let local = Local::now();
println!("{}", local);
// Stop application on disconnect
System::current().stop();
}
}
impl WebsocketClient {
fn hb(&self, ctx: &mut Context<Self>) {
ctx.run_later(Duration::new(1, 0), |act, ctx| {
act.sink_write.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 server websocket messages
impl StreamHandler<Result<Frame, WsProtocolError>> for WebsocketClient {
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!("StreamHandler disconnected");
let local = Local::now();
println!("{}", local);
ctx.stop()
}
}
impl actix::io::WriteHandler<WsProtocolError> for WebsocketClient {}
fn main() {
let sys = System::new("websocket-client");
let local: DateTime<Local> = Local::now();
println!("{}", local);
Arbiter::spawn(async {
let (_, framed) = Client::new()
// .ws("http://127.0.0.1:8080/ws/")
.ws("ws://hq.sinajs.cn/wskt?list=s_sh000001")
.connect()
.await
.map_err(|e| {
println!("Error: {}", e);
})
.unwrap();
let (sink, stream) = framed.split();
WebsocketClient::create(|ctx| {
WebsocketClient::add_stream(stream, ctx);
WebsocketClient{ sink_write: SinkWrite::new(sink, ctx) }
});
});
sys.run().unwrap();
}