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
use std::io;
use std::iter::{Take, Repeat, repeat};
use result::{WebSocketResult, WebSocketError};
use dataframe::{DataFrame, Opcode};
use byteorder::{WriteBytesExt, BigEndian};
use ws::util::message::message_from_data;
use ws;
#[derive(PartialEq, Clone, Debug)]
pub enum Message {
Text(String),
Binary(Vec<u8>),
Close(Option<CloseData>),
Ping(Vec<u8>),
Pong(Vec<u8>),
}
impl ws::Message<DataFrame> for Message {
type DataFrameIterator = Take<Repeat<DataFrame>>;
fn from_dataframes(frames: Vec<DataFrame>) -> WebSocketResult<Message> {
let mut iter = frames.iter();
let first = try!(iter.next().ok_or(WebSocketError::ProtocolError(
"No dataframes provided".to_string()
)));
let mut data = first.data.clone();
if first.reserved != [false; 3] {
return Err(WebSocketError::ProtocolError(
"Unsupported reserved bits received".to_string()
));
}
for dataframe in iter {
if dataframe.opcode != Opcode::Continuation {
return Err(WebSocketError::ProtocolError(
"Unexpected non-continuation data frame".to_string()
));
}
if dataframe.reserved != [false; 3] {
return Err(WebSocketError::ProtocolError(
"Unsupported reserved bits received".to_string()
));
}
for i in dataframe.data.iter() {
data.push(*i);
}
}
message_from_data(first.opcode, data)
}
fn into_iter(self) -> Take<Repeat<DataFrame>> {
let (opcode, data) = match self {
Message::Text(payload) => (Opcode::Text, payload.into_bytes()),
Message::Binary(payload) => (Opcode::Binary, payload),
Message::Close(payload) => (
Opcode::Close,
match payload {
Some(payload) => { payload.into_bytes().unwrap() }
None => { Vec::new() }
}
),
Message::Ping(payload) => (Opcode::Ping, payload),
Message::Pong(payload) => (Opcode::Pong, payload),
};
let dataframe = DataFrame::new(true, opcode, data);
repeat(dataframe).take(1)
}
}
#[derive(PartialEq, Clone, Debug)]
pub struct CloseData {
pub status_code: u16,
pub reason: String,
}
impl CloseData {
pub fn new(status_code: u16, reason: String) -> CloseData {
CloseData {
status_code: status_code,
reason: reason,
}
}
pub fn into_bytes(self) -> io::Result<Vec<u8>> {
let mut buf = Vec::new();
try!(buf.write_u16::<BigEndian>(self.status_code));
for i in self.reason.as_bytes().iter() {
buf.push(*i);
}
Ok(buf)
}
}