[][src]Trait websocket::server::upgrade::async::IntoWs

pub trait IntoWs {
    type Stream: Stream;
    type Error;
    fn into_ws(
        self
    ) -> Box<dyn Future<Item = Upgrade<Self::Stream>, Error = Self::Error> + Send>; }

Trait to take a stream or similar and attempt to recover the start of a websocket handshake from it (asynchronously). Should be used when a stream might contain a request for a websocket session.

If an upgrade request can be parsed, one can accept or deny the handshake with the WsUpgrade struct. Otherwise the original stream is returned along with an error.

Note: the stream is owned because the websocket client expects to own its stream.

This is already implemented for all async streams, which means all types with AsyncRead + AsyncWrite + 'static ('static because the future wants to own the stream).

Example

use websocket::async::{TcpListener, TcpStream};
use websocket::async::futures::{Stream, Future};
use websocket::async::server::upgrade::IntoWs;
use websocket::sync::Client;

let mut runtime = tokio::runtime::Builder::new().build().unwrap();
let executor = runtime.executor();
let addr = "127.0.0.1:80".parse().unwrap();
let listener = TcpListener::bind(&addr).unwrap();

let websocket_clients = listener
    .incoming().map_err(|e| e.into())
    .and_then(|stream| stream.into_ws().map_err(|e| e.3))
    .map(|upgrade| {
        if upgrade.protocols().iter().any(|p| p == "super-cool-proto") {
            let accepted = upgrade
                .use_protocol("super-cool-proto")
                .accept()
                .map(|_| ()).map_err(|_| ());

            executor.spawn(accepted);
        } else {
            let rejected = upgrade.reject()
                .map(|_| ()).map_err(|_| ());

            executor.spawn(rejected);
        }
    });

Associated Types

type Stream: Stream

The type of stream this upgrade process is working with (TcpStream, etc.)

type Error

An error value in case the stream is not asking for a websocket connection or something went wrong. It is common to also include the stream here.

Loading content...

Required methods

fn into_ws(
    self
) -> Box<dyn Future<Item = Upgrade<Self::Stream>, Error = Self::Error> + Send>

Attempt to read and parse the start of a Websocket handshake, later with the returned WsUpgrade struct, call accept to start a websocket client, andreject` to send a handshake rejection response.

Note: this is the asynchronous version, meaning it will not block when trying to read a request.

Loading content...

Implementors

impl<S> IntoWs for S where
    S: Stream + Send + 'static, 
[src]

type Stream = S

type Error = (S, Option<Request>, BytesMut, HyperIntoWsError)

Loading content...