Skip to content

Instantly share code, notes, and snippets.

@Victory
Created December 23, 2014 23:02
Show Gist options
  • Save Victory/13faa35826067fced52d to your computer and use it in GitHub Desktop.
Save Victory/13faa35826067fced52d to your computer and use it in GitHub Desktop.
why move stream
// this moves stream
fn send (&self,
mut stream: &mut BufferedStream<TcpStream>) {
let msg = match self.payload {
Payload::Text(ref s) => s.as_bytes(),
Payload::Binary(ref s) => s.as_slice(),
Payload::Empty => "".as_bytes(),
};
let length = msg.len() as u8;
println!("fin: {}, msg: {}, opcode: {}", self.fin, msg, self.opcode as u8);
stream.write_u8(self.fin | self.opcode as u8).unwrap();
stream.write_u8(length).unwrap();
stream.write(msg).unwrap();
stream.flush();
}
// this does not move stream
fn from_stream(mut stream: &mut BufferedStream<TcpStream>) -> Message {
let cur_byte: u8 = stream.read_byte().unwrap();
let fin = cur_byte & 0b1000_0000;
let rsv = cur_byte & 0b0111_0000;
let opc = cur_byte & 0b0000_1111;
let msk = cur_byte & 0b0000_0001;
let cur_byte: u8 = stream.read_byte().unwrap();
let len = (cur_byte & 0b0111_1111) as uint;
let mskkey = stream.read_exact(4).unwrap();
let mut msg = Vec::new();
for ii in range(0u, len) {
let cur_byte: u8 = stream.read_byte().unwrap();
let ch = mskkey[ii % 4] ^ cur_byte;
msg.push(ch);
}
let utf8_msg = match String::from_utf8(msg) {
Ok(m) => m,
Err(_) => panic!("I don't know how to ut8 that")
};
println!(
"fin {}, rsv {}, msk {}, opcode {}, len {}, mskkey {}, msg {}",
fin, rsv, msk, opc, len, mskkey, utf8_msg);
let payload = Payload::Text(utf8_msg);
return Message::from_payload(payload, fin);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment