Function jsonrpsee_server::ws::connect

source ·
pub async fn connect<L, B>(
    req: HttpRequest<B>,
    server_cfg: ServerConfig,
    methods: impl Into<Methods>,
    conn: ConnectionState,
    rpc_middleware: RpcServiceBuilder<L>,
) -> Result<(HttpResponse, impl Future<Output = ()>), HttpResponse>
where L: for<'a> Layer<RpcService>, for<'a> <L as Layer<RpcService>>::Service: Send + Sync + 'static + RpcServiceT<'a>,
Expand description

Low-level API that tries to upgrade the HTTP connection to a WebSocket connection.

Returns Ok((http_response, conn_fut)) if the WebSocket connection was successfully established otherwise Err(http_response).

conn_fut is a future that drives the WebSocket connection and if it’s dropped the connection will be closed.

Because this API depends on hyper the response needs to be sent to complete the HTTP request.

use jsonrpsee_server::{ws, ServerConfig, Methods, ConnectionState, HttpRequest, HttpResponse};
use jsonrpsee_server::middleware::rpc::{RpcServiceBuilder, RpcServiceT, RpcService};

async fn handle_websocket_conn<L>(
    req: HttpRequest,
    server_cfg: ServerConfig,
    methods: impl Into<Methods> + 'static,
    conn: ConnectionState,
    rpc_middleware: RpcServiceBuilder<L>,
    mut disconnect: tokio::sync::mpsc::Receiver<()>
) -> HttpResponse
where
    L: for<'a> tower::Layer<RpcService> + 'static,
    <L as tower::Layer<RpcService>>::Service: Send + Sync + 'static,
    for<'a> <L as tower::Layer<RpcService>>::Service: RpcServiceT<'a> + 'static,
{
  match ws::connect(req, server_cfg, methods, conn, rpc_middleware).await {
    Ok((rp, conn_fut)) => {
        tokio::spawn(async move {
            // Keep the connection alive until
            // a close signal is sent.
            tokio::select! {
                _ = conn_fut => (),
                _ = disconnect.recv() => (),
            }
        });
        rp
    }
    Err(rp) => rp,
  }
}