2 #![feature(cursor_remaining)]
7 use byteorder::{BigEndian, WriteBytesExt};
8 pub use client::{connect, Sender as Client};
9 use num_enum::TryFromPrimitive;
17 pub const PROTO_ID: u32 = 0x4f457403;
18 pub const UDP_PKT_SIZE: usize = 512;
19 pub const NUM_CHANS: usize = 3;
20 pub const REL_BUFFER: usize = 0x8000;
21 pub const INIT_SEQNUM: u16 = 65500;
23 pub trait UdpSender: Send + Sync + 'static {
24 fn send(&self, data: Vec<u8>) -> io::Result<()>;
27 pub trait UdpReceiver: Send + Sync + 'static {
28 fn recv(&self) -> io::Result<Vec<u8>>;
31 #[derive(Debug, Copy, Clone)]
38 #[derive(Debug, Copy, Clone, PartialEq, TryFromPrimitive)]
47 #[derive(Debug, Copy, Clone, PartialEq, TryFromPrimitive)]
63 pub type Error = error::Error;
64 pub type InPkt = Result<Pkt<Vec<u8>>, Error>;
70 pub struct RudpShare<S: UdpSender> {
73 pub chans: Vec<AckChan>,
78 pub struct RudpReceiver<S: UdpSender> {
79 share: Arc<RudpShare<S>>,
80 pkt_rx: mpsc::Receiver<InPkt>,
84 pub struct RudpSender<S: UdpSender> {
85 share: Arc<RudpShare<S>>,
88 impl<S: UdpSender> RudpShare<S> {
89 pub fn send(&self, tp: PktType, pkt: Pkt<&[u8]>) -> io::Result<()> {
90 let mut buf = Vec::with_capacity(4 + 2 + 1 + 1 + pkt.data.len());
91 buf.write_u32::<BigEndian>(PROTO_ID)?;
92 buf.write_u16::<BigEndian>(self.remote_id)?;
93 buf.write_u8(pkt.chan as u8)?;
94 buf.write_u8(tp as u8)?;
97 self.udp_tx.send(buf)?;
103 impl<S: UdpSender> RudpSender<S> {
104 pub fn send(&self, pkt: Pkt<&[u8]>) -> io::Result<()> {
105 self.share.send(PktType::Orig, pkt) // TODO
109 impl<S: UdpSender> ops::Deref for RudpReceiver<S> {
110 type Target = mpsc::Receiver<InPkt>;
112 fn deref(&self) -> &Self::Target {
117 pub fn new<S: UdpSender, R: UdpReceiver>(
122 ) -> (RudpSender<S>, RudpReceiver<S>) {
123 let (pkt_tx, pkt_rx) = mpsc::channel();
125 let share = Arc::new(RudpShare {
129 chans: (0..NUM_CHANS).map(|_| AckChan).collect(),
131 let recv_share = Arc::clone(&share);
134 recv_worker::RecvWorker::new(udp_rx, recv_share, pkt_tx).run();
139 share: Arc::clone(&share),
141 RudpReceiver { share, pkt_rx },
147 fn main() -> io::Result<()> {
148 //println!("{}", x.deep_size_of());
149 let (tx, rx) = connect("127.0.0.1:30000")?;
151 let mut mtpkt = vec![];
152 mtpkt.write_u16::<BigEndian>(2)?; // high level type
153 mtpkt.write_u8(29)?; // serialize ver
154 mtpkt.write_u16::<BigEndian>(0)?; // compression modes
155 mtpkt.write_u16::<BigEndian>(40)?; // MinProtoVer
156 mtpkt.write_u16::<BigEndian>(40)?; // MaxProtoVer
157 mtpkt.write_u16::<BigEndian>(3)?; // player name length
158 mtpkt.write(b"foo")?; // player name
166 while let Ok(result) = rx.recv() {
169 io::stdout().write(pkt.data.as_slice())?;
171 Err(err) => eprintln!("Error: {}", err),