From 0992071a7f1a36424bcfaf1fbc84541ea041df1a Mon Sep 17 00:00:00 2001 From: hozan23 Date: Thu, 11 Apr 2024 10:19:20 +0200 Subject: add support for tokio & improve net crate api --- net/src/connection.rs | 53 +++++++++++---------------------------------------- 1 file changed, 11 insertions(+), 42 deletions(-) (limited to 'net/src/connection.rs') diff --git a/net/src/connection.rs b/net/src/connection.rs index fa4640f..bbd21de 100644 --- a/net/src/connection.rs +++ b/net/src/connection.rs @@ -1,65 +1,34 @@ use async_trait::async_trait; -use crate::{ - transports::{tcp, udp, unix}, - Endpoint, Error, Result, -}; +use crate::{Endpoint, Result}; /// Alias for `Box` -pub type Conn = Box; +pub type Conn = Box>; /// A trait for objects which can be converted to [`Conn`]. pub trait ToConn { - fn to_conn(self) -> Conn; + type Item; + fn to_conn(self) -> Conn; } /// Connection is a generic network connection interface for -/// [`udp::UdpConn`], [`tcp::TcpConn`], and [`unix::UnixConn`]. +/// [`udp::UdpConn`], [`tcp::TcpConn`], [`tls::TlsConn`], [`ws::WsConn`], +/// and [`unix::UnixConn`]. /// /// If you are familiar with the Go language, this is similar to the /// [Conn](https://pkg.go.dev/net#Conn) interface #[async_trait] pub trait Connection: Send + Sync { + type Item; /// Returns the remote peer endpoint of this connection fn peer_endpoint(&self) -> Result; /// Returns the local socket endpoint of this connection fn local_endpoint(&self) -> Result; - /// Reads data from this connection. - async fn read(&self, buf: &mut [u8]) -> Result; + /// Recvs data from this connection. + async fn recv(&self) -> Result; - /// Writes data to this connection - async fn write(&self, buf: &[u8]) -> Result; -} - -/// Connects to the provided endpoint. -/// -/// it only supports `tcp4/6`, `udp4/6`, and `unix`. -/// -/// #Example -/// -/// ``` -/// use karyon_net::{Endpoint, dial}; -/// -/// async { -/// let endpoint: Endpoint = "tcp://127.0.0.1:3000".parse().unwrap(); -/// -/// let conn = dial(&endpoint).await.unwrap(); -/// -/// conn.write(b"MSG").await.unwrap(); -/// -/// let mut buffer = [0;32]; -/// conn.read(&mut buffer).await.unwrap(); -/// }; -/// -/// ``` -/// -pub async fn dial(endpoint: &Endpoint) -> Result { - match endpoint { - Endpoint::Tcp(_, _) => Ok(Box::new(tcp::dial(endpoint).await?)), - Endpoint::Udp(_, _) => Ok(Box::new(udp::dial(endpoint).await?)), - Endpoint::Unix(addr) => Ok(Box::new(unix::dial(addr).await?)), - _ => Err(Error::InvalidEndpoint(endpoint.to_string())), - } + /// Sends data to this connection + async fn send(&self, msg: Self::Item) -> Result<()>; } -- cgit v1.2.3