forked from yutiansut/qatrader-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocketclient.rs
147 lines (122 loc) · 3.6 KB
/
websocketclient.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
//! Simple websocket client.
use serde::{Serialize, Deserialize};
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 futures::{
lazy,
stream::{SplitSink, Stream},
Future,
};
pub fn wsmain() {
::std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
let sys = actix::System::new("ws-example");
Arbiter::spawn(lazy(|| {
Client::new()
.ws("ws:https://www.yutiansut.com:7988")
.connect()
.map_err(|e| {
println!("Error: {}", e);
})
.map(|(response, framed)| {
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));
});
})
}));
let _ = sys.run();
}
struct ChatClient<T>(SinkWrite<SplitSink<Framed<T, Codec>>>)
where
T: AsyncRead + AsyncWrite;
#[derive(Message)]
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(String::new())).unwrap();
act.hb(ctx);
// client should also check for a timeout here, similar to the
// server code
});
}
}
#[derive(Serialize, Deserialize, Debug)]
struct Broker {
aid: String,
brokers: Vec<String>
}
/// 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<Frame, WsProtocolError> for ChatClient<T>
where
T: AsyncRead + AsyncWrite,
{
fn handle(&mut self, msg: Frame, _ctx: &mut Context<Self>) {
if let Frame::Text(txt) = msg {
let res = txt.unwrap();
let xu = std::str::from_utf8(&res).unwrap();
println!("{:?}",xu);
let u: Broker = serde_json::from_str(&xu).unwrap();
println!("{}", serde_json::to_string(&u).unwrap());
}
}
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
{
}