Skip to main content

Connection

Struct Connection 

Source
pub struct Connection { /* private fields */ }
Available on crate feature std only.
Expand description

A blocking server connection: ServerConn driven over a TcpStream.

Use it for your own accept loop, or to keep the socket after an upgrade with into_upgraded.

§Examples

use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use http_net::{blocking::Connection, Limits, Response};

let listener = TcpListener::bind("127.0.0.1:0")?;
let addr = listener.local_addr()?;
let client = std::thread::spawn(move || -> std::io::Result<Vec<u8>> {
    let mut s = TcpStream::connect(addr)?;
    s.write_all(b"POST /sum HTTP/1.1\r\nHost: x\r\nContent-Length: 3\r\nConnection: close\r\n\r\n1 2")?;
    let mut reply = Vec::new();
    s.read_to_end(&mut reply)?;
    Ok(reply)
});

let (stream, _) = listener.accept()?;
let mut conn = Connection::new(stream, Limits::new());
while let Some(req) = conn.next_request()? {
    let sum: u32 = std::str::from_utf8(req.body())?.split(' ').filter_map(|n| n.parse::<u32>().ok()).sum();
    let response = Response::text(200, &sum.to_string());
    conn.respond(&response)?;
}
conn.close();
let reply = client.join().unwrap()?;
assert!(reply.ends_with(b"\r\n\r\n3"));

Implementations§

Source§

impl Connection

Source

pub fn new(stream: TcpStream, limits: Limits) -> Self

Wraps an accepted socket. Set its timeouts first if you want them: the read timeout set on stream is the idle timeout, and with_request_timeout adds a deadline for each request as a whole.

§Examples

See Connection.

Source

pub fn with_response_deadline(self, deadline: Option<Duration>) -> Self

Sets a deadline for writing each response, from its first byte to its last, a streamed body included (see ServerConfig::with_response_deadline). When it passes, the write fails with an Error::Io of kind TimedOut; close the connection then (the response cannot be finished). None (the default for a bare Connection) leaves only the socket’s own write timeout.

§Examples
use std::time::Duration;
let conn = http_net::blocking::Connection::new(stream, http_net::Limits::new())
    .with_response_deadline(Some(Duration::from_secs(60)));
Source

pub fn with_request_timeout(self, timeout: Option<Duration>) -> Self

Sets a deadline for each request: from the moment its first byte is seen to the end of its body (see ServerConfig::with_request_timeout). When it passes, next_request fails with an Error::Io of kind TimedOut. None (the default for a bare Connection) leaves only the socket’s own read timeout.

§Examples
use std::time::Duration;
let conn = http_net::blocking::Connection::new(stream, http_net::Limits::new())
    .with_request_timeout(Some(Duration::from_secs(10)));
Source

pub fn next_request(&mut self) -> Result<Option<Incoming<'_>>, Error>

Reads the next complete request. Ok(None) means the connection is finished (the client closed between requests, the previous exchange ended with connection: close, or the connection was upgraded).

A request that carries Expect: 100-continue is answered with 100 Continue before its body is read. Other expectations are left to the caller (see RequestHead::has_unknown_expectation); Server answers them with 417.

§Errors

Error::Http for a request this crate refuses (answer it with its HttpError::status and close), Error::Io for socket failures and timeouts (including the request deadline, as TimedOut), and Error::Http with HttpError::InvalidState if the previous request has not been answered.

§Examples

See Connection.

Source

pub fn respond(&mut self, response: &Response) -> Result<(), Error>

Writes response to the socket. A streamed response continues with send_body and end_body.

§Errors

Error::Http when the response is invalid or out of order (see ServerConn::respond); Error::Io when the write fails.

§Examples

See Connection.

Source

pub fn send_informational(&mut self, response: &Response) -> Result<(), Error>

Writes an interim response (for example 103 Early Hints) before the final one, through ServerConn::send_informational.

§Errors

As ServerConn::send_informational, plus Error::Io.

§Examples
use http_net::Response;

conn.send_informational(&Response::new(103).header("link", "</app.css>; rel=preload; as=style"))?;
conn.respond(&Response::text(200, "page"))?;
Source

pub fn send_body(&mut self, data: &[u8]) -> Result<(), Error>

Writes body bytes of a streamed response.

§Errors

As ServerConn::send_body, plus Error::Io.

§Examples
conn.respond(&http_net::Response::new(200).chunked())?;
conn.send_body(b"first")?;
conn.end_body()?;
Source

pub fn end_body(&mut self) -> Result<(), Error>

Ends a streamed response.

§Errors

As ServerConn::end_body, plus Error::Io.

§Examples

See send_body.

Source

pub fn is_upgraded(&self) -> bool

Whether a 101 (or a 2xx to CONNECT) was sent.

§Examples

See into_upgraded.

Source

pub fn into_upgraded(self) -> Option<Upgraded>

The socket and the bytes of the new protocol, after an upgrade; None if the connection was not upgraded. The socket’s read timeout is the one it had when the Connection was created (a request deadline may have shortened it while the request was read).

§Examples
if conn.is_upgraded() {
    let up = conn.into_upgraded().unwrap();
    // speak the new protocol on up.stream, starting with up.leftover
}
Source

pub fn close(self)

Closes the connection gracefully: stops sending, briefly drains what the client is still sending, and drops the socket.

§Examples

See Connection.

Trait Implementations§

Source§

impl Debug for Connection

The buffers print as lengths only: they hold the last request body and the last serialized response, which may carry credentials.

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

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<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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.