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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#![deny(
missing_docs,
unused_must_use,
unused_mut,
unused_imports,
unused_import_braces)]
extern crate futures;
extern crate tokio_io;
pub extern crate tungstenite;
#[cfg(feature="connect")]
mod connect;
#[cfg(feature="stream")]
pub mod stream;
use std::io::ErrorKind;
use futures::{Poll, Future, Async, AsyncSink, Stream, Sink, StartSend};
use tokio_io::{AsyncRead, AsyncWrite};
use tungstenite::{
error::Error as WsError,
handshake::{
HandshakeRole, HandshakeError,
client::{ClientHandshake, Response, Request},
server::{ServerHandshake, Callback, NoCallback},
},
protocol::{WebSocket, Message, Role, WebSocketConfig},
server,
};
#[cfg(feature="connect")]
pub use connect::{connect_async, client_async_tls};
#[cfg(all(feature="connect", feature="tls"))]
pub use connect::MaybeTlsStream;
pub fn client_async<'a, R, S>(
request: R,
stream: S,
) -> ConnectAsync<S>
where
R: Into<Request<'a>>,
S: AsyncRead + AsyncWrite
{
client_async_with_config(request, stream, None)
}
pub fn client_async_with_config<'a, R, S>(
request: R,
stream: S,
config: Option<WebSocketConfig>,
) -> ConnectAsync<S>
where
R: Into<Request<'a>>,
S: AsyncRead + AsyncWrite
{
ConnectAsync {
inner: MidHandshake {
inner: Some(ClientHandshake::start(stream, request.into(), config).handshake())
}
}
}
pub fn accept_async<S>(stream: S) -> AcceptAsync<S, NoCallback>
where
S: AsyncRead + AsyncWrite,
{
accept_hdr_async(stream, NoCallback)
}
pub fn accept_async_with_config<S>(
stream: S,
config: Option<WebSocketConfig>,
) -> AcceptAsync<S, NoCallback>
where
S: AsyncRead + AsyncWrite,
{
accept_hdr_async_with_config(stream, NoCallback, config)
}
pub fn accept_hdr_async<S, C>(stream: S, callback: C) -> AcceptAsync<S, C>
where
S: AsyncRead + AsyncWrite,
C: Callback,
{
accept_hdr_async_with_config(stream, callback, None)
}
pub fn accept_hdr_async_with_config<S, C>(
stream: S,
callback: C,
config: Option<WebSocketConfig>,
) -> AcceptAsync<S, C>
where
S: AsyncRead + AsyncWrite,
C: Callback,
{
AcceptAsync {
inner: MidHandshake {
inner: Some(server::accept_hdr_with_config(stream, callback, config))
}
}
}
pub struct WebSocketStream<S> {
inner: WebSocket<S>,
}
impl<S> WebSocketStream<S> {
pub fn from_raw_socket(
stream: S,
role: Role,
config: Option<WebSocketConfig>,
) -> Self {
let ws = WebSocket::from_raw_socket(stream, role, config);
WebSocketStream { inner: ws }
}
pub fn from_partially_read(
stream: S,
part: Vec<u8>,
role: Role,
config: Option<WebSocketConfig>,
) -> Self {
let ws = WebSocket::from_partially_read(stream, part, role, config);
WebSocketStream { inner: ws }
}
}
impl<T> Stream for WebSocketStream<T> where T: AsyncRead + AsyncWrite {
type Item = Message;
type Error = WsError;
fn poll(&mut self) -> Poll<Option<Message>, WsError> {
self.inner.read_message().map(|m| Some(m)).to_async()
}
}
impl<T> Sink for WebSocketStream<T> where T: AsyncRead + AsyncWrite {
type SinkItem = Message;
type SinkError = WsError;
fn start_send(&mut self, item: Message) -> StartSend<Message, WsError> {
self.inner.write_message(item).to_start_send()
}
fn poll_complete(&mut self) -> Poll<(), WsError> {
self.inner.write_pending().to_async()
}
fn close(&mut self) -> Poll<(), WsError> {
self.inner.close(None).to_async()
}
}
pub struct ConnectAsync<S: AsyncRead + AsyncWrite> {
inner: MidHandshake<ClientHandshake<S>>,
}
impl<S: AsyncRead + AsyncWrite> Future for ConnectAsync<S> {
type Item = (WebSocketStream<S>, Response);
type Error = WsError;
fn poll(&mut self) -> Poll<Self::Item, WsError> {
match self.inner.poll()? {
Async::NotReady => Ok(Async::NotReady),
Async::Ready((ws, resp)) => Ok(Async::Ready((WebSocketStream { inner: ws }, resp))),
}
}
}
pub struct AcceptAsync<S: AsyncRead + AsyncWrite, C: Callback> {
inner: MidHandshake<ServerHandshake<S, C>>,
}
impl<S: AsyncRead + AsyncWrite, C: Callback> Future for AcceptAsync<S, C> {
type Item = WebSocketStream<S>;
type Error = WsError;
fn poll(&mut self) -> Poll<Self::Item, WsError> {
match self.inner.poll()? {
Async::NotReady => Ok(Async::NotReady),
Async::Ready(ws) => Ok(Async::Ready(WebSocketStream { inner: ws })),
}
}
}
struct MidHandshake<H: HandshakeRole> {
inner: Option<Result<<H as HandshakeRole>::FinalResult, HandshakeError<H>>>,
}
impl<H: HandshakeRole> Future for MidHandshake<H> {
type Item = <H as HandshakeRole>::FinalResult;
type Error = WsError;
fn poll(&mut self) -> Poll<Self::Item, WsError> {
match self.inner.take().expect("cannot poll MidHandshake twice") {
Ok(result) => Ok(Async::Ready(result)),
Err(HandshakeError::Failure(e)) => Err(e),
Err(HandshakeError::Interrupted(s)) => {
match s.handshake() {
Ok(result) => Ok(Async::Ready(result)),
Err(HandshakeError::Failure(e)) => Err(e),
Err(HandshakeError::Interrupted(s)) => {
self.inner = Some(Err(HandshakeError::Interrupted(s)));
Ok(Async::NotReady)
}
}
}
}
}
}
trait ToAsync {
type T;
type E;
fn to_async(self) -> Result<Async<Self::T>, Self::E>;
}
impl<T> ToAsync for Result<T, WsError> {
type T = T;
type E = WsError;
fn to_async(self) -> Result<Async<Self::T>, Self::E> {
match self {
Ok(x) => Ok(Async::Ready(x)),
Err(error) => match error {
WsError::Io(ref err) if err.kind() == ErrorKind::WouldBlock => Ok(Async::NotReady),
err => Err(err),
},
}
}
}
trait ToStartSend {
type T;
type E;
fn to_start_send(self) -> StartSend<Self::T, Self::E>;
}
impl ToStartSend for Result<(), WsError> {
type T = Message;
type E = WsError;
fn to_start_send(self) -> StartSend<Self::T, Self::E> {
match self {
Ok(_) => Ok(AsyncSink::Ready),
Err(error) => match error {
WsError::Io(ref err) if err.kind() == ErrorKind::WouldBlock => Ok(AsyncSink::Ready),
WsError::SendQueueFull(msg) => Ok(AsyncSink::NotReady(msg)),
err => Err(err),
}
}
}
}