1 //! This crate provides a simple brokerless message-queue abstraction over asynchronous network
5 //! When building networked applications, developers shouldn't have to focus on repeatedly solving
6 //! the problem of reliable, fault-tolerant message delivery over byte-streams. By using a message
7 //! queue abstraction, crate users can focus on core application logic and leave the low-level
8 //! networking and message-queue guarantees to the abstraction.
11 //! Please use the [examples](https://github.com/sachanganesh/connect-rs/tree/main/examples)
12 //! provided to help understand crate usage.
21 pub use crate::protocol::{ConnectDatagram, DatagramEmptyError};
22 pub use crate::reader::ConnectionReader;
23 pub use crate::writer::ConnectionWriter;
24 use async_std::{net::SocketAddr, pin::Pin};
25 use futures::{AsyncRead, AsyncWrite};
26 pub use futures::{SinkExt, StreamExt};
28 /// Wrapper around a [`ConnectionReader`] and [`ConnectionWriter`] to read and write on a network
30 pub struct Connection {
31 reader: ConnectionReader,
32 writer: ConnectionWriter,
38 local_addr: SocketAddr,
39 peer_addr: SocketAddr,
40 read_stream: Pin<Box<dyn AsyncRead + Send + Sync>>,
41 write_stream: Pin<Box<dyn AsyncWrite + Send + Sync>>,
44 reader: ConnectionReader::new(local_addr, peer_addr, read_stream),
45 writer: ConnectionWriter::new(local_addr, peer_addr, write_stream),
49 /// Get the local IP address and port.
50 pub fn local_addr(&self) -> SocketAddr {
51 self.reader.local_addr()
54 /// Get the peer IP address and port.
55 pub fn peer_addr(&self) -> SocketAddr {
56 self.reader.peer_addr()
59 /// Consume the [`Connection`] to split into separate [`ConnectionReader`] and
60 /// [`ConnectionWriter`] halves.
62 /// [`Connection`]s are split when reading and writing must be concurrent operations.
63 pub fn split(self) -> (ConnectionReader, ConnectionWriter) {
64 (self.reader, self.writer)
67 /// Re-wrap the [`ConnectionReader`] and [`ConnectionWriter`] halves into a [`Connection`].
68 pub fn join(reader: ConnectionReader, writer: ConnectionWriter) -> Self {
69 Self { reader, writer }
72 /// Get mutable access to the underlying [`ConnectionReader`].
73 pub fn reader(&mut self) -> &mut ConnectionReader {
77 /// Get mutable access to the underlying [`ConnectionWriter`].
78 pub fn writer(&mut self) -> &mut ConnectionWriter {
82 /// Close the connection by closing both the reading and writing halves.
83 pub async fn close(self) -> SocketAddr {
84 let peer_addr = self.peer_addr();
85 let (reader, writer) = self.split();
89 // writer.close().await;