Skip to main content

ReqSocket

Struct ReqSocket 

Source
pub struct ReqSocket<S = TcpStream>
where S: AsyncRead + AsyncWrite + Unpin,
{ /* private fields */ }
Expand description

A REQ socket for synchronous request-reply patterns.

REQ sockets enforce strict alternation between send and receive:

  • Must call send() before recv()
  • Must call recv() before next send()

They’re used for:

  • Synchronous RPC clients
  • Request-reply protocols
  • Client-server communication

§ZeroMQ Compatibility

Compatible with zmq::REQ and zmq::REP sockets from libzmq.

§Example

use monocoque::zmq::ReqSocket;
use bytes::Bytes;

// Connect to server
let mut socket = ReqSocket::connect("127.0.0.1:5555").await?;

// Send request
socket.send(vec![Bytes::from("REQUEST")]).await?;

// Must receive before next send
if let Ok(Some(reply)) = socket.recv().await {
    println!("Got reply: {:?}", reply);
}

// Now can send again
socket.send(vec![Bytes::from("ANOTHER")]).await?;
if let Ok(Some(reply)) = socket.recv().await {
    println!("Got reply: {:?}", reply);
}

Implementations§

Source§

impl ReqSocket

Source

pub async fn connect(endpoint: &str) -> Result<Self>

Connect to a ZeroMQ peer and create a REQ socket.

Supports both TCP and IPC endpoints:

  • TCP: "tcp://127.0.0.1:5555" or "127.0.0.1:5555"
  • IPC: "ipc:///tmp/socket.sock" (Unix only)
§Arguments
  • endpoint - Endpoint to connect to
§Errors

Returns an error if the connection or handshake fails.

§Example
use monocoque::zmq::ReqSocket;

let socket = ReqSocket::connect("tcp://127.0.0.1:5555").await?;
Source

pub fn is_connected(&self) -> bool

Check if the socket is currently connected.

Source

pub async fn try_reconnect(&mut self) -> Result<()>

Try to reconnect to the stored endpoint.

Source

pub async fn send_with_reconnect(&mut self, msg: Vec<Bytes>) -> Result<()>

Send with automatic reconnection on network error.

Source

pub async fn recv_with_reconnect(&mut self) -> Result<Option<Vec<Bytes>>>

Receive with automatic reconnection on EOF or network error.

Source

pub async fn connect_with_options( endpoint: &str, options: SocketOptions, ) -> Result<Self>

Connect to a ZeroMQ peer with custom socket options.

This allows configuring timeouts and other options before connection.

§Example
use monocoque::zmq::ReqSocket;
use monocoque::SocketOptions;
use std::time::Duration;

let options = SocketOptions::default()
    .with_send_timeout(Duration::from_secs(5))
    .with_recv_timeout(Duration::from_secs(10));

let socket = ReqSocket::connect_with_options(
    "tcp://127.0.0.1:5555",
    options
).await?;
Source

pub async fn connect_ipc(path: &str) -> Result<ReqSocket<UnixStream>>

Connect to a ZeroMQ peer via IPC (Unix domain sockets).

Unix-only. Accepts IPC paths with or without ipc:// prefix.

§Example
use monocoque::zmq::ReqSocket;

let socket = ReqSocket::connect_ipc("/tmp/req.sock").await?;
Source

pub async fn from_tcp(stream: TcpStream) -> Result<Self>

Create a REQ socket from a TCP stream with TCP_NODELAY enabled.

Source

pub async fn from_tcp_with_options( stream: TcpStream, options: SocketOptions, ) -> Result<Self>

Create a REQ socket from a TCP stream with custom socket options.

Source

pub async fn with_options<Stream>( stream: Stream, options: SocketOptions, ) -> Result<ReqSocket<Stream>>
where Stream: AsyncRead + AsyncWrite + Unpin,

Create a REQ socket from any stream with custom options.

Source§

impl<S> ReqSocket<S>
where S: AsyncRead + AsyncWrite + Unpin,

Source

pub fn monitor(&mut self) -> SocketMonitor

Enable monitoring for this socket.

Returns a receiver for socket lifecycle events.

Source

pub async fn send(&mut self, msg: Vec<Bytes>) -> Result<()>

Send a multipart message.

This enforces the REQ state machine - you must call recv() before calling send() again.

§Arguments
  • msg - Vector of message frames (parts)
§Errors

Returns an error if:

  • Called while awaiting a reply (must call recv() first)
  • The underlying connection is closed
§Example
use monocoque::zmq::ReqSocket;
use bytes::Bytes;

// Send single-part message
socket.send(vec![Bytes::from("Hello")]).await?;

// Send multi-part message
socket.send(vec![
    Bytes::from("Part 1"),
    Bytes::from("Part 2"),
]).await?;
Source

pub const fn socket_type() -> SocketType

Get the socket type.

§ZeroMQ Compatibility

Corresponds to ZMQ_TYPE (16) option.

Source

pub fn last_endpoint(&self) -> Option<&Endpoint>

Get the endpoint this socket is connected/bound to, if available.

Returns None if the socket was created from a raw stream.

§ZeroMQ Compatibility

Corresponds to ZMQ_LAST_ENDPOINT (32) option.

Source

pub fn has_more(&self) -> bool

Check if the last received message has more frames coming.

Returns true if there are more frames in the current multipart message.

§ZeroMQ Compatibility

Corresponds to ZMQ_RCVMORE (13) option.

Source

pub fn events(&self) -> u32

Get the event state of the socket.

Returns a bitmask indicating ready-to-receive and ready-to-send states.

§Returns
  • 1 (POLLIN) - Socket is ready to receive
  • 2 (POLLOUT) - Socket is ready to send
  • 3 (POLLIN | POLLOUT) - Socket is ready for both
§ZeroMQ Compatibility

Corresponds to ZMQ_EVENTS (15) option.

Source

pub async fn recv(&mut self) -> Result<Option<Vec<Bytes>>>

Receive a multipart message.

This blocks until a reply is received. You must call this after send() before calling send() again.

§Returns
  • Ok(Some(msg)) - Received a multipart message
  • Ok(None) - Connection closed gracefully (peer disconnected)
  • Err(e) - Network or I/O error
§Example
use monocoque::zmq::ReqSocket;

if let Some(reply) = socket.recv().await? {
    for (i, frame) in reply.iter().enumerate() {
        println!("Frame {}: {:?}", i, frame);
    }
}
Source

pub const fn options(&self) -> &SocketOptions

Get a reference to the socket options.

§Example
use monocoque::zmq::ReqSocket;

let timeout = socket.options().recv_timeout;
println!("Receive timeout: {:?}", timeout);
Source

pub fn options_mut(&mut self) -> &mut SocketOptions

Get a mutable reference to the socket options.

§Example
use monocoque::zmq::ReqSocket;
use std::time::Duration;

socket.options_mut().recv_timeout = Some(Duration::from_secs(30));
Source

pub fn set_options(&mut self, options: SocketOptions)

Set the socket options.

§Example
use monocoque::zmq::ReqSocket;
use monocoque::SocketOptions;
use std::time::Duration;

let options = SocketOptions::default()
    .with_send_timeout(Duration::from_secs(5))
    .with_recv_timeout(Duration::from_secs(10));

socket.set_options(options);
Source§

impl ReqSocket<UnixStream>

Source

pub async fn from_unix_stream(stream: UnixStream) -> Result<Self>

Create a REQ socket from an existing Unix domain socket stream (IPC).

Source

pub async fn from_unix_stream_with_options( stream: UnixStream, options: SocketOptions, ) -> Result<Self>

Create a REQ socket from an existing Unix stream with custom options.

This method provides full control over socket behavior through SocketOptions.

Auto Trait Implementations§

§

impl<S = TcpStream> !Freeze for ReqSocket<S>

§

impl<S> RefUnwindSafe for ReqSocket<S>
where S: RefUnwindSafe,

§

impl<S> Send for ReqSocket<S>
where S: Send,

§

impl<S> Sync for ReqSocket<S>
where S: Sync,

§

impl<S> Unpin for ReqSocket<S>

§

impl<S> UnsafeUnpin for ReqSocket<S>
where S: UnsafeUnpin,

§

impl<S> UnwindSafe for ReqSocket<S>
where S: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more