#sockets #tungstenite #tokio #web

ws-endpoint

A WebSocket API endpoint implemented in Rust

1 unstable release

0.1.0 Jul 8, 2020

#8 in #tungstenite

MIT license

12KB
188 lines

Websocket Endpoint

A generic asynchronous tokio and tungstenite based web socket endpoint implementation. This is not actually a real library but more a building block for websocket based application that wants to provide a request/response API.

To use it, just create a new WsEndpoint instance with an appropriate processor (a function taking in a request, e.g. as a JSON String, and returning an encoded response) and start it with the socket address you want it to run at.

Here's a minimal example (may be out of date, check the 'echo' example for the latest version):

extern crate ws_endpoint;

use std::io;
use ws_endpoint::WsEndpoint;

#[tokio::main]
async fn main() -> io::Result<()> {
    let endpoint = WsEndpoint::new_sync_text_endpoint(process);
    endpoint.start("127.0.0.1:5000").await
}

async fn process(request: String) -> Option<String> {
    // We are just echoing here.
    // In a real world scenario this would be
    // the place to parse and process the
    // request and return a proper response.
    let response = request;

    Some(response)
}

Dependencies

~11MB
~195K SLoC