diff options
Diffstat (limited to 'src/main.rs')
| -rw-r--r-- | src/main.rs | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..9df3beb --- /dev/null +++ b/src/main.rs @@ -0,0 +1,84 @@ +use bytes::BytesMut; +//use rust_unix_server::codec_eth::EthCodec; +//use rust_unix_server::codec_ipv4::IPv4Codec; +//use rust_unix_server::codec_tcp::TcpCodec; +use rust_unix_server::codec_pkt::PktCodec; +use std::io; +use tokio::net::UnixListener; +use tokio_stream::StreamExt; +use tokio_util::codec::Decoder; +use tokio_util::codec::Encoder; + +#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Default)] +pub struct MyCodec<C>(C); + +impl<C> MyCodec<C> { + pub fn new(c: C) -> Self { + MyCodec(c) + } +} + +impl<C> Decoder for MyCodec<C> +where + C: Decoder, + std::io::Error: From<<C as Decoder>::Error>, +{ + type Item = C::Item; + type Error = io::Error; + + fn decode(&mut self, data: &mut BytesMut) -> Result<Option<Self::Item>, io::Error> { + if !data.is_empty() { + println!("MyCodec -> decode(), handle data len: {}", data.len()); + + let decoded = self.0.decode(data)?; + match decoded { + None => { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("Frame of length {} is too large.", 111), + )); + } + Some(inner) => Ok(Some(inner)), + } + } else { + Ok(None) + } + } +} + +impl<C, T> Encoder<T> for MyCodec<C> +where + C: Encoder<T>, + std::io::Error: From<C::Error>, +{ + type Error = io::Error; + + fn encode(&mut self, _item: T, _buf: &mut BytesMut) -> Result<(), io::Error> { + // TODO + Ok(()) + } +} + +// nc -U /Users/lwp/Downloads/temp.sock +#[tokio::main] +async fn main() -> Result<(), Box<dyn std::error::Error>> { + let listener = UnixListener::bind("/Users/lwp/Downloads/temp.sock")?; + loop { + let (socket, _) = listener.accept().await?; + + tokio::spawn(async move { + let mut framed = tokio_util::codec::Framed::new( + socket, + // MyCodec::new(EthCodec::new(IPv4Codec::new(TcpCodec::new()))), + PktCodec::new(), + ); + while let Some(message) = framed.next().await { + match message { + Ok(bytes) => println!("bytes: {:?}", bytes), + Err(err) => println!("Socket closed with error: {:?}", err), + } + } + println!("Client closed the connection"); + }); + } +} |
