pub struct Connection { /* private fields */ }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
impl Connection
Sourcepub fn new(stream: TcpStream, limits: Limits) -> Self
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.
Sourcepub fn with_response_deadline(self, deadline: Option<Duration>) -> Self
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)));Sourcepub fn with_request_timeout(self, timeout: Option<Duration>) -> Self
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)));Sourcepub fn next_request(&mut self) -> Result<Option<Incoming<'_>>, Error>
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.
Sourcepub fn respond(&mut self, response: &Response) -> Result<(), Error>
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.
Sourcepub fn send_informational(&mut self, response: &Response) -> Result<(), Error>
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"))?;Sourcepub fn send_body(&mut self, data: &[u8]) -> Result<(), Error>
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()?;Sourcepub fn is_upgraded(&self) -> bool
pub fn is_upgraded(&self) -> bool
Sourcepub fn into_upgraded(self) -> Option<Upgraded>
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
}Sourcepub fn close(self)
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.