blitz_ws/
server.rs

1//! Utilities to accept an incoming WebSocket connection on a server
2
3use std::io::{Read, Write};
4
5use crate::{
6    error::Result,
7    handshake::{
8        core::HandshakeError,
9        server::{Callback, NoCallback, ServerHandshake},
10    },
11    protocol::{config::WebSocketConfig, websocket::WebSocket},
12};
13
14/// Accept the given Stream as a WebSocket.
15///
16/// This function starts a server WebSocket handshake over the given stream.
17/// If you want TLS support, use `native_tls::TlsStream`, `rustls::Stream` or
18/// `openssl::ssl::SslStream` for the stream here. Any `Read + Write` streams are supported,
19/// including those from `Mio` and others.
20pub fn accept<S: Read + Write>(
21    stream: S,
22) -> Result<WebSocket<S>, HandshakeError<ServerHandshake<S, NoCallback>>> {
23    accept_with_config(stream, None)
24}
25
26/// Accept the given Stream as a WebSocket.
27///
28/// Uses a configuration provided as an argument. Calling it with `None` will use the default one
29/// used by `accept()`.
30///
31/// This function starts a server WebSocket handshake over the given stream.
32/// If you want TLS support, use `native_tls::TlsStream`, `rustls::Stream` or
33/// `openssl::ssl::SslStream` for the stream here. Any `Read + Write` streams are supported,
34/// including those from `Mio` and others.
35pub fn accept_with_config<S: Read + Write>(
36    stream: S,
37    config: Option<WebSocketConfig>,
38) -> Result<WebSocket<S>, HandshakeError<ServerHandshake<S, NoCallback>>> {
39    accept_header_with_config(stream, NoCallback, config)
40}
41
42/// Accept the given Stream as a WebSocket.
43///
44/// Uses a configuration provided as an argument. Calling it with `None` will use the default one
45/// used by `accept_hdr()`.
46///
47/// This function does the same as `accept()` but accepts an extra callback
48/// for header processing. The callback receives headers of the incoming
49/// requests and is able to add extra headers to the reply.
50pub fn accept_header_with_config<S: Read + Write, C: Callback>(
51    stream: S,
52    callback: C,
53    config: Option<WebSocketConfig>,
54) -> Result<WebSocket<S>, HandshakeError<ServerHandshake<S, C>>> {
55    ServerHandshake::start(stream, callback, config).handshake()
56}
57
58/// Accept the given Stream as a WebSocket.
59///
60/// This function does the same as `accept()` but accepts an extra callback
61/// for header processing. The callback receives headers of the incoming
62/// requests and is able to add extra headers to the reply.
63pub fn accept_header<S: Read + Write, C: Callback>(
64    stream: S,
65    callback: C,
66) -> Result<WebSocket<S>, HandshakeError<ServerHandshake<S, C>>> {
67    accept_header_with_config(stream, callback, None)
68}