tungstenite/
server.rs

1//! Methods to accept an incoming WebSocket connection on a server.
2
3pub use crate::handshake::server::ServerHandshake;
4
5use crate::handshake::{
6    server::{Callback, NoCallback},
7    HandshakeError,
8};
9
10use crate::protocol::{WebSocket, WebSocketConfig};
11
12use std::io::{Read, Write};
13
14/// Accept the given Stream as a WebSocket.
15///
16/// Uses a configuration provided as an argument. Calling it with `None` will use the default one
17/// used by `accept()`.
18///
19/// This function starts a server WebSocket handshake over the given stream.
20/// If you want TLS support, use `native_tls::TlsStream`, `rustls::Stream` or
21/// `openssl::ssl::SslStream` for the stream here. Any `Read + Write` streams are supported,
22/// including those from `Mio` and others.
23pub fn accept_with_config<S: Read + Write>(
24    stream: S,
25    config: Option<WebSocketConfig>,
26) -> Result<WebSocket<S>, HandshakeError<ServerHandshake<S, NoCallback>>> {
27    accept_hdr_with_config(stream, NoCallback, config)
28}
29
30/// Accept the given Stream as a WebSocket.
31///
32/// This function starts a server WebSocket handshake over the given stream.
33/// If you want TLS support, use `native_tls::TlsStream`, `rustls::Stream` or
34/// `openssl::ssl::SslStream` for the stream here. Any `Read + Write` streams are supported,
35/// including those from `Mio` and others.
36pub fn accept<S: Read + Write>(
37    stream: S,
38) -> Result<WebSocket<S>, HandshakeError<ServerHandshake<S, NoCallback>>> {
39    accept_with_config(stream, None)
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_hdr_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_hdr<S: Read + Write, C: Callback>(
64    stream: S,
65    callback: C,
66) -> Result<WebSocket<S>, HandshakeError<ServerHandshake<S, C>>> {
67    accept_hdr_with_config(stream, callback, None)
68}