2 #![feature(cursor_remaining)]
7 use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
8 pub use client::{connect, Sender as Client};
9 use num_enum::{TryFromPrimitive, TryFromPrimitiveError};
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 type Error = error::Error;
25 pub trait UdpSender: Send + Sync + 'static {
26 fn send(&self, data: Vec<u8>) -> io::Result<()>;
29 pub trait UdpReceiver: Send + Sync + 'static {
30 fn recv(&self) -> io::Result<Vec<u8>>;
33 #[derive(Debug, Copy, Clone)]
40 #[derive(Debug, Copy, Clone, PartialEq, TryFromPrimitive)]
49 #[derive(Debug, Copy, Clone, PartialEq, TryFromPrimitive)]
65 pub type InPkt = Result<Pkt<Vec<u8>>, Error>;
71 pub struct RudpShare<S: UdpSender> {
74 pub chans: Vec<AckChan>,
79 pub struct RudpReceiver<S: UdpSender> {
80 share: Arc<RudpShare<S>>,
81 pkt_rx: mpsc::Receiver<InPkt>,
85 pub struct RudpSender<S: UdpSender> {
86 share: Arc<RudpShare<S>>,
89 impl<S: UdpSender> RudpShare<S> {
90 pub fn new(id: u16, remote_id: u16, udp_tx: S) -> Self {
95 chans: (0..NUM_CHANS).map(|_| AckChan).collect(),
99 pub fn send(&self, tp: PktType, pkt: Pkt<&[u8]>) -> io::Result<()> {
100 let mut buf = Vec::with_capacity(4 + 2 + 1 + 1 + pkt.data.len());
101 buf.write_u32::<BigEndian>(PROTO_ID)?;
102 buf.write_u16::<BigEndian>(self.remote_id)?;
103 buf.write_u8(pkt.chan as u8)?;
104 buf.write_u8(tp as u8)?;
105 buf.write(pkt.data)?;
107 self.udp_tx.send(buf)?;
113 impl<S: UdpSender> RudpSender<S> {
114 pub fn send(&self, pkt: Pkt<&[u8]>) -> io::Result<()> {
115 self.share.send(PktType::Orig, pkt) // TODO
119 impl<S: UdpSender> ops::Deref for RudpReceiver<S> {
120 type Target = mpsc::Receiver<InPkt>;
122 fn deref(&self) -> &Self::Target {
127 pub fn new<S: UdpSender, R: UdpReceiver>(
132 ) -> (RudpSender<S>, RudpReceiver<S>) {
133 let (pkt_tx, pkt_rx) = mpsc::channel();
135 let share = Arc::new(RudpShare::new(id, remote_id, udp_tx));
136 let recv_share = Arc::clone(&share);
138 thread::spawn(move || {
139 recv_worker::RecvWorker::new(udp_rx, recv_share, pkt_tx).run();
144 share: Arc::clone(&share),
146 RudpReceiver { share, pkt_rx },
152 fn main() -> io::Result<()> {
153 //println!("{}", x.deep_size_of());
154 let (tx, rx) = connect("127.0.0.1:30000")?;
156 let mut mtpkt = vec![];
157 mtpkt.write_u16::<BigEndian>(2)?; // high level type
158 mtpkt.write_u8(29)?; // serialize ver
159 mtpkt.write_u16::<BigEndian>(0)?; // compression modes
160 mtpkt.write_u16::<BigEndian>(40)?; // MinProtoVer
161 mtpkt.write_u16::<BigEndian>(40)?; // MaxProtoVer
162 mtpkt.write_u16::<BigEndian>(3)?; // player name length
163 mtpkt.write(b"foo")?; // player name
171 while let Ok(result) = rx.recv() {
174 io::stdout().write(pkt.data.as_slice())?;
176 Err(err) => eprintln!("Error: {}", err),