1 //! This crate provides a simple brokerless message-queue abstraction over asynchronous network
5 //! Please use the [example programs](https://github.com/sachanganesh/connect-rs/tree/main/examples)
6 //! provided to help understand crate usage.
9 //! When building networked applications, developers shouldn't have to focus on repeatedly solving
10 //! the problem of reliable, fault-tolerant message delivery over byte-streams. By using a message
11 //! queue abstraction, crate users can focus on core application logic and leave the low-level
12 //! networking and message-queue guarantees to the abstraction.
22 #[cfg(feature = "tls")]
23 #[doc(cfg(feature = "tls"))]
26 use async_std::{net::SocketAddr, pin::Pin};
27 use futures::{AsyncRead, AsyncWrite};
29 pub use crate::protocol::{ConnectDatagram, DatagramError};
30 pub use crate::reader::ConnectionReader;
31 pub use crate::writer::{ConnectionWriteError, ConnectionWriter};
32 pub use futures::{SinkExt, StreamExt};
34 /// Wrapper around a [`ConnectionReader`] and [`ConnectionWriter`] to read and write on a network
36 pub struct Connection {
37 reader: ConnectionReader,
38 writer: ConnectionWriter,
44 local_addr: SocketAddr,
45 peer_addr: SocketAddr,
46 read_stream: Pin<Box<dyn AsyncRead + Send + Sync>>,
47 write_stream: Pin<Box<dyn AsyncWrite + Send + Sync>>,
50 reader: ConnectionReader::new(local_addr, peer_addr, read_stream),
51 writer: ConnectionWriter::new(local_addr, peer_addr, write_stream),
55 /// Get the local IP address and port.
56 pub fn local_addr(&self) -> SocketAddr {
57 self.reader.local_addr()
60 /// Get the peer IP address and port.
61 pub fn peer_addr(&self) -> SocketAddr {
62 self.reader.peer_addr()
65 /// Consume the [`Connection`] to split into separate [`ConnectionReader`] and
66 /// [`ConnectionWriter`] halves.
68 /// [`Connection`]s are split when reading and writing must be concurrent operations.
69 pub fn split(self) -> (ConnectionReader, ConnectionWriter) {
70 (self.reader, self.writer)
73 /// Re-wrap the [`ConnectionReader`] and [`ConnectionWriter`] halves into a [`Connection`].
74 pub fn join(reader: ConnectionReader, writer: ConnectionWriter) -> Self {
75 Self { reader, writer }
78 /// Get mutable access to the underlying [`ConnectionReader`].
79 pub fn reader(&mut self) -> &mut ConnectionReader {
83 /// Get mutable access to the underlying [`ConnectionWriter`].
84 pub fn writer(&mut self) -> &mut ConnectionWriter {
88 /// Close the connection by closing both the reading and writing halves.
89 pub async fn close(self) -> SocketAddr {
90 let peer_addr = self.peer_addr();
91 let (reader, writer) = self.split();
95 // writer.close().await;