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
use super::Task;
use crate::callback::Callback;
use crate::format::{Binary, Text};
use stdweb::traits::IMessageEvent;
use stdweb::web::event::{SocketCloseEvent, SocketErrorEvent, SocketMessageEvent, SocketOpenEvent};
use stdweb::web::{IEventTarget, SocketBinaryType, SocketReadyState, WebSocket};
#[derive(Debug)]
pub enum WebSocketStatus {
Opened,
Closed,
Error,
}
#[must_use]
pub struct WebSocketTask {
ws: WebSocket,
notification: Callback<WebSocketStatus>,
}
#[derive(Default)]
pub struct WebSocketService {}
impl WebSocketService {
pub fn new() -> Self {
Self {}
}
pub fn connect<OUT: 'static>(
&mut self,
url: &str,
callback: Callback<OUT>,
notification: Callback<WebSocketStatus>,
) -> WebSocketTask
where
OUT: From<Text> + From<Binary>,
{
let ws = WebSocket::new(url).unwrap();
ws.set_binary_type(SocketBinaryType::ArrayBuffer);
let notify = notification.clone();
ws.add_event_listener(move |_: SocketOpenEvent| {
notify.emit(WebSocketStatus::Opened);
});
let notify = notification.clone();
ws.add_event_listener(move |_: SocketCloseEvent| {
notify.emit(WebSocketStatus::Closed);
});
let notify = notification.clone();
ws.add_event_listener(move |_: SocketErrorEvent| {
notify.emit(WebSocketStatus::Error);
});
ws.add_event_listener(move |event: SocketMessageEvent| {
if let Some(bytes) = event.data().into_array_buffer() {
let bytes: Vec<u8> = bytes.into();
let data = Ok(bytes);
let out = OUT::from(data);
callback.emit(out);
} else if let Some(text) = event.data().into_text() {
let data = Ok(text);
let out = OUT::from(data);
callback.emit(out);
}
});
WebSocketTask { ws, notification }
}
}
impl WebSocketTask {
pub fn send<IN>(&mut self, data: IN)
where
IN: Into<Text>,
{
if let Ok(body) = data.into() {
if self.ws.send_text(&body).is_err() {
self.notification.emit(WebSocketStatus::Error);
}
}
}
pub fn send_binary<IN>(&mut self, data: IN)
where
IN: Into<Binary>,
{
if let Ok(body) = data.into() {
if self.ws.send_bytes(&body).is_err() {
self.notification.emit(WebSocketStatus::Error);
}
}
}
}
impl Task for WebSocketTask {
fn is_active(&self) -> bool {
self.ws.ready_state() == SocketReadyState::Open
}
fn cancel(&mut self) {
self.ws.close();
}
}
impl Drop for WebSocketTask {
fn drop(&mut self) {
if self.is_active() {
self.cancel();
}
}
}