WebSockets

The Rest Server library has web socket support using the underlying NetCoreServer library. The library supports a basic (unencrypted, “ws://”) websocket that can be used to send and receive WebsocketMessage from the server.

Usage

The same usage principles regarding Security and MultiThreading apply to the Websocket Endpoint as well. WebSocket endpoints can be registered with

_endpointId = Server.EndpointCollection.RegisterWebsocketEndpoint("/websocket", message => {
    // Handle incoming messages
    Debug.Log($"Received message: {message}");
});

It is possible to register multiple endpoints, but only one endpoint per path. The endpoint id can be used to send information to the registered clients.

Server.WsSend(_endpointId, /* Text or binary data */");

All clients that are connected to the endpoint will receive the message and the message is sent asynchronously. The collection stored in the property Server.WsSessionCollection can be used to determine the number of connected clients.

Clients can establish a connection by using the “ws://” protocol. On server side the websocket upgrade is always allowed when RegisterWebsocketEndpoint matches. This can be controlled with new SpecialHandlers:

  • AllowWsUpgradeRequest: Called when a websocket upgrade request would be allowed.
  • NoWsUpgradeRequest: Called when a websocket upgrade request was sent to a non-websocket endpoint.
  • WsAuthHandler: Called after the websocket upgrade request was accepted and before the websocket session is created.

Example

See the Websocket Example