Created
May 6, 2014 02:28
-
-
Save misterhat/973a0a4eda81b3f8b1ad to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io::{TcpListener, TcpStream}; | |
use std::io::net::ip::{Ipv4Addr, SocketAddr}; | |
use std::io::{Acceptor, Listener}; | |
fn decode_packet<T: Reader>(stream: &mut T) -> (u8, Vec<u8>) { | |
let mut length = stream.read_byte().unwrap() as uint; | |
if length >= 160 { | |
length = (length - 160) * 256; | |
length += stream.read_byte().unwrap() as uint; | |
let id = stream.read_byte().unwrap(); | |
let payload = stream.read_exact(length).unwrap(); | |
(id, payload) | |
} else { | |
if length > 0 { | |
length -= 1; | |
let last = stream.read_byte().unwrap(); | |
let id = stream.read_byte().unwrap(); | |
let mut payload = stream.read_exact(length - 1).unwrap(); | |
payload.push(last); | |
(id, payload) | |
} else { | |
let id = stream.read_byte().unwrap(); | |
(id, vec!()) | |
} | |
} | |
} | |
fn handle_client(mut stream: TcpStream) { | |
loop { | |
let decoded = decode_packet(&mut stream); | |
println!("{}", decoded); | |
} | |
} | |
fn main() { | |
let listener = TcpListener::bind(SocketAddr { | |
ip: Ipv4Addr(127, 0, 0, 1), | |
port: 43594 | |
}); | |
let mut acceptor = listener.listen(); | |
for stream in acceptor.incoming() { | |
match stream { | |
Err(_) => { | |
println!("oH NO fail"); | |
}, | |
Ok(stream) => spawn(proc() { | |
handle_client(stream); | |
}) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment