[][src]Struct websocket::server::WsServer

pub struct WsServer<S, L> where
    S: OptionalTlsAcceptor
{ pub ssl_acceptor: S, // some fields omitted }

Represents a WebSocket server which can work with either normal (non-secure) connections, or secure WebSocket connections.

This is a convenient way to implement WebSocket servers, however it is possible to use any sendable Reader and Writer to obtain a WebSocketClient, so if needed, an alternative server implementation can be used.

Synchronous Servers

Synchronous implementations of a websocket server are available below, each method is documented so the reader knows whether is it synchronous or asynchronous.

To use the synchronous implementation, you must have the sync feature enabled (it is enabled by default). To use the synchronous SSL implementation, you must have the sync-ssl feature enabled (it is enabled by default).

Asynchronous Servers

Asynchronous implementations of a websocket server are available below, each method is documented so the reader knows whether is it synchronous or asynchronous. Simply look out for the implementation of Server whose methods only return Futures (it is also written in the docs if the method is async).

To use the asynchronous implementation, you must have the async feature enabled (it is enabled by default). To use the asynchronous SSL implementation, you must have the async-ssl feature enabled (it is enabled by default).

A Hyper Server

This crates comes with hyper integration out of the box, you can create a hyper server and serve websocket and HTTP on the same port! check out the docs over at websocket::server::upgrade::sync::HyperRequest for an example.

A Custom Server

So you don't want to use any of our server implementations? That's O.K. All it takes is implementing the IntoWs trait for your server's streams, then calling .into_ws() on them. check out the docs over at websocket::server::upgrade::sync for more.

Fields

ssl_acceptor: S

The SSL acceptor given to the server

Methods

impl<S> WsServer<S, TcpListener> where
    S: OptionalTlsAcceptor
[src]

pub fn local_addr(&self) -> Result<SocketAddr>[src]

Get the socket address of this server

impl WsServer<NoTlsAcceptor, TcpListener>[src]

Asynchronous methods for creating an async server and accepting incoming connections.

pub fn bind<A: ToSocketAddrs>(addr: A, handle: &Handle) -> Result<Self>[src]

Bind a websocket server to an address. Creating a websocket server can be done immediately so this does not return a Future but a simple Result.

pub fn incoming(self) -> Incoming<TcpStream>[src]

Turns the server into a stream of connection objects.

Each item of the stream is the address of the incoming connection and an Upgrade struct which lets the user decide whether to turn the connection into a websocket connection or reject it.

See the [examples/async-server.rs] (https://github.com/cyderize/rust-websocket/blob/master/examples/async-server.rs) example for a good echo server example.

impl WsServer<TlsAcceptor, TcpListener>[src]

Asynchronous methods for creating an async SSL server and accepting incoming connections.

pub fn bind_secure<A: ToSocketAddrs>(
    addr: A,
    acceptor: TlsAcceptor,
    handle: &Handle
) -> Result<Self>
[src]

Bind an SSL websocket server to an address. Creating a websocket server can be done immediately so this does not return a Future but a simple Result.

Since this is an SSL server one needs to provide a TlsAcceptor that contains the server's SSL information.

pub fn incoming(self) -> Incoming<TlsStream<TcpStream>>[src]

Turns the server into a stream of connection objects.

Each item of the stream is the address of the incoming connection and an Upgrade struct which lets the user decide whether to turn the connection into a websocket connection or reject it.

See the [examples/async-server.rs] (https://github.com/cyderize/rust-websocket/blob/master/examples/async-server.rs) example for a good echo server example.

impl<S> WsServer<S, TcpListener> where
    S: OptionalTlsAcceptor
[src]

Synchronous methods for creating a server and accepting incoming connections.

pub fn local_addr(&self) -> Result<SocketAddr>[src]

Get the socket address of this server

pub fn set_nonblocking(&self, nonblocking: bool) -> Result<()>[src]

Changes whether the Server is in nonblocking mode. NOTE: It is strongly encouraged to use the websocket::async module instead of this. It provides high level APIs for creating asynchronous servers.

If it is in nonblocking mode, accept() will return an error instead of blocking when there are no incoming connections.

 // Suppose we have to work in a single thread, but want to
 // accomplish two unrelated things:
 // (1) Once in a while we want to check if anybody tried to connect to
 // our websocket server, and if so, handle the TcpStream.
 // (2) In between we need to something else, possibly unrelated to networking.

 let mut server = Server::bind("127.0.0.1:0").unwrap();

 // Set the server to non-blocking.
 server.set_nonblocking(true);

 for i in 1..3 {
 	let result = match server.accept() {
 		Ok(wsupgrade) => {
 			// Do something with the established TcpStream.
 		}
 		_ => {
 			// Nobody tried to connect, move on.
 		}
 	};
 	// Perform another task. Because we have a non-blocking server,
 	// this will execute independent of whether someone tried to
 	// establish a connection.
 	let two = 1+1;
 }

pub fn into_async(self, handle: &Handle) -> Result<Server<S>>[src]

Turns an existing synchronous server into an asynchronous one. This will only work if the stream used for this server S already implements AsyncRead + AsyncWrite. Useful if you would like some blocking things to happen at the start of your server.

impl WsServer<TlsAcceptor, TcpListener>[src]

Synchronous methods for creating an SSL server and accepting incoming connections.

pub fn bind_secure<A>(addr: A, acceptor: TlsAcceptor) -> Result<Self> where
    A: ToSocketAddrs
[src]

Bind this Server to this socket, utilising the given SslContext

Secure Servers

extern crate websocket;
extern crate native_tls;
use std::thread;
use std::io::Read;
use std::fs::File;
use websocket::Message;
use websocket::sync::Server;
use native_tls::{Identity, TlsAcceptor};

// In this example we retrieve our keypair and certificate chain from a PKCS #12 archive,
// but but they can also be retrieved from, for example, individual PEM- or DER-formatted
// files. See the documentation for the `PKey` and `X509` types for more details.
let mut file = File::open("identity.pfx").unwrap();
let mut pkcs12 = vec![];
file.read_to_end(&mut pkcs12).unwrap();
let pkcs12 = Identity::from_pkcs12(&pkcs12, "hacktheplanet").unwrap();

let acceptor = TlsAcceptor::builder(pkcs12).build().unwrap();

let server = Server::bind_secure("127.0.0.1:1234", acceptor).unwrap();

for connection in server.filter_map(Result::ok) {
    // Spawn a new thread for each connection.
    thread::spawn(move || {
		    let mut client = connection.accept().unwrap();

		    let message = Message::text("Hello, client!");
		    let _ = client.send_message(&message);

		    // ...
    });
}

pub fn accept(&mut self) -> AcceptResult<TlsStream<TcpStream>>[src]

Wait for and accept an incoming WebSocket connection, returning a WebSocketRequest

impl WsServer<NoTlsAcceptor, TcpListener>[src]

pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<Self>[src]

Bind this Server to this socket

Non-secure Servers

extern crate websocket;
use std::thread;
use websocket::Message;
use websocket::sync::Server;

let server = Server::bind("127.0.0.1:1234").unwrap();

for connection in server.filter_map(Result::ok) {
    // Spawn a new thread for each connection.
    thread::spawn(move || {
	      let mut client = connection.accept().unwrap();

	      let message = Message::text("Hello, client!");
	      let _ = client.send_message(&message);

	      // ...
   });
}

pub fn accept(&mut self) -> AcceptResult<TcpStream>[src]

Wait for and accept an incoming WebSocket connection, returning a WebSocketRequest

pub fn try_clone(&self) -> Result<Self>[src]

Create a new independently owned handle to the underlying socket.

Trait Implementations

impl Iterator for WsServer<TlsAcceptor, TcpListener>[src]

type Item = AcceptResult<TlsStream<TcpStream>>

The type of the elements being iterated over.

impl Iterator for WsServer<NoTlsAcceptor, TcpListener>[src]

type Item = AcceptResult<TcpStream>

The type of the elements being iterated over.

Auto Trait Implementations

impl<S, L> Send for WsServer<S, L> where
    L: Send,
    S: Send

impl<S, L> Sync for WsServer<S, L> where
    L: Sync,
    S: Sync

impl<S, L> Unpin for WsServer<S, L> where
    L: Unpin,
    S: Unpin

impl<S, L> UnwindSafe for WsServer<S, L> where
    L: UnwindSafe,
    S: UnwindSafe

impl<S, L> RefUnwindSafe for WsServer<S, L> where
    L: RefUnwindSafe,
    S: RefUnwindSafe

Blanket Implementations

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> From<T> for T[src]

impl<I> IntoIterator for I where
    I: Iterator
[src]

type Item = <I as Iterator>::Item

The type of the elements being iterated over.

type IntoIter = I

Which kind of iterator are we turning this into?

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Typeable for T where
    T: Any

impl<I> UnicodeNormalization<I> for I where
    I: Iterator<Item = char>, 

impl<I> IteratorRandom for I where
    I: Iterator
[src]

impl<V, T> VZip<V> for T where
    V: MultiLane<T>, 

impl<I> IteratorRandom for I where
    I: Iterator
[src]