pub struct IncomingStream { /* private fields */ }
Expand description
A stream of incoming connections.
IncomingStream::bind
is the primary entrypoint for constructing a new IncomingStream
.
Incoming connections will be usually passed to a Server
instance to be handled.
Check out Server::bind
or
Server::listen
for more information.
Implementations§
source§impl IncomingStream
impl IncomingStream
sourcepub async fn bind(addr: SocketAddr) -> Result<Self>
pub async fn bind(addr: SocketAddr) -> Result<Self>
Create a new IncomingStream
by binding to a socket address.
The socket will be configured to be non-blocking and reuse the address.
§Example
use std::net::SocketAddr;
use pavex::server::{IncomingStream, Server};
let addr = SocketAddr::from(([127, 0, 0, 1], 8080));
let incoming = IncomingStream::bind(addr).await?;
§Custom configuration
If you want to customize the options set on the socket, you can build your own
TcpListener
using [socket2::Socket
] and then convert it
into an IncomingStream
via TryFrom::try_from
.
There’s only one option you can’t change: the socket will always be set to non-blocking
mode.
use std::net::SocketAddr;
use socket2::Domain;
use pavex::server::{IncomingStream, Server};
let addr = SocketAddr::from(([127, 0, 0, 1], 8080));
let socket = socket2::Socket::new(
Domain::for_address(addr),
socket2::Type::STREAM,
Some(socket2::Protocol::TCP),
)
.expect("Failed to create a socket");
socket.set_reuse_address(true)?;
socket.set_nonblocking(true)?;
socket.bind(&addr.into())?;
// We customize the backlog setting!
socket.listen(2048_i32)?;
let listener = std::net::TcpListener::from(socket);
let incoming: IncomingStream = listener.try_into()?;
sourcepub fn local_addr(&self) -> Result<SocketAddr>
pub fn local_addr(&self) -> Result<SocketAddr>
Returns the address that this IncomingStream
is bound to.
sourcepub async fn accept(&self) -> Result<(TcpStream, SocketAddr)>
pub async fn accept(&self) -> Result<(TcpStream, SocketAddr)>
Accepts a new incoming connection from the underlying listener.
This function will yield once a new TCP connection is established. When
established, the corresponding [TcpStream
] and the remote peer’s
address will be returned.
§Example
use pavex::server::IncomingStream;
use std::net::SocketAddr;
let address = SocketAddr::from(([127, 0, 0, 1], 8080));
let incoming = IncomingStream::bind(address).await?;
match incoming.accept().await {
Ok((_socket, addr)) => println!("new client: {:?}", addr),
Err(e) => println!("couldn't get client: {:?}", e),
}