2 #![feature(cursor_remaining)]
3 #![feature(hash_drain_filter)]
4 #![feature(async_fn_in_trait)]
9 use byteorder::{BigEndian, WriteBytesExt};
10 pub use client::{connect, Sender as Client};
11 use num_enum::TryFromPrimitive;
12 use std::future::Future;
18 use tokio::sync::mpsc;
20 pub const PROTO_ID: u32 = 0x4f457403;
21 pub const UDP_PKT_SIZE: usize = 512;
22 pub const NUM_CHANS: usize = 3;
23 pub const REL_BUFFER: usize = 0x8000;
24 pub const INIT_SEQNUM: u16 = 65500;
25 pub const TIMEOUT: u64 = 30;
27 pub trait UdpSender: Send + Sync + 'static {
28 async fn send(&self, data: Vec<u8>) -> io::Result<()>;
31 pub trait UdpReceiver: Send + Sync + 'static {
32 async fn recv(&self) -> io::Result<Vec<u8>>;
35 #[derive(Debug, Copy, Clone)]
42 #[derive(Debug, Copy, Clone, PartialEq, TryFromPrimitive)]
51 #[derive(Debug, Copy, Clone, PartialEq, TryFromPrimitive)]
67 pub type Error = error::Error;
68 pub type InPkt = Result<Pkt<Vec<u8>>, Error>;
74 pub struct RudpShare<S: UdpSender> {
77 pub chans: Vec<AckChan>,
82 pub struct RudpReceiver<S: UdpSender> {
83 share: Arc<RudpShare<S>>,
84 pkt_rx: mpsc::UnboundedReceiver<InPkt>,
88 pub struct RudpSender<S: UdpSender> {
89 share: Arc<RudpShare<S>>,
92 impl<S: UdpSender> RudpShare<S> {
93 pub async fn send(&self, tp: PktType, pkt: Pkt<&[u8]>) -> io::Result<()> {
94 let mut buf = Vec::with_capacity(4 + 2 + 1 + 1 + pkt.data.len());
95 buf.write_u32::<BigEndian>(PROTO_ID)?;
96 buf.write_u16::<BigEndian>(self.remote_id)?;
97 buf.write_u8(pkt.chan as u8)?;
98 buf.write_u8(tp as u8)?;
101 self.udp_tx.send(buf).await?;
107 impl<S: UdpSender> RudpSender<S> {
108 pub async fn send(&self, pkt: Pkt<&[u8]>) -> io::Result<()> {
109 self.share.send(PktType::Orig, pkt).await // TODO
113 impl<S: UdpSender> ops::Deref for RudpReceiver<S> {
114 type Target = mpsc::UnboundedReceiver<InPkt>;
116 fn deref(&self) -> &Self::Target {
121 pub fn new<S: UdpSender, R: UdpReceiver>(
126 ) -> (RudpSender<S>, RudpReceiver<S>) {
127 let (pkt_tx, pkt_rx) = mpsc::unbounded_channel();
129 let share = Arc::new(RudpShare {
133 chans: (0..NUM_CHANS).map(|_| AckChan).collect(),
135 let recv_share = Arc::clone(&share);
137 tokio::spawn(async { recv_worker::RecvWorker::new(udp_rx, recv_share, pkt_tx).await });
141 share: Arc::clone(&share),
143 RudpReceiver { share, pkt_rx },
150 async fn main() -> io::Result<()> {
151 //println!("{}", x.deep_size_of());
152 let (tx, rx) = connect("127.0.0.1:30000").await?;
154 let mut mtpkt = vec![];
155 mtpkt.write_u16::<BigEndian>(2)?; // high level type
156 mtpkt.write_u8(29)?; // serialize ver
157 mtpkt.write_u16::<BigEndian>(0)?; // compression modes
158 mtpkt.write_u16::<BigEndian>(40)?; // MinProtoVer
159 mtpkt.write_u16::<BigEndian>(40)?; // MaxProtoVer
160 mtpkt.write_u16::<BigEndian>(3)?; // player name length
161 mtpkt.write(b"foo")?; // player name
170 while let Some(result) = rx.recv().await {
173 io::stdout().write(pkt.data.as_slice())?;
175 Err(err) => eprintln!("Error: {}", err),