Skip to content

Server side events

pablocar80 edited this page Aug 11, 2019 · 2 revisions

Overview of server events (i.e. events triggered by the server)

It's possible to trigger events from the server. For example, a page with real-time information can receive updates from the server as changes happen, without having the client continually querying the data.

In order to enable server-side events on a page, first we must enable them on the page:

LaraUI.Page.JSBridge.ServerEventsOn();  // and disable with ServerEventsOff()

The reason for enabling server-side events manually is scalability. Server-side events require an open WebSocket for the client to listen to incoming server-side events, and servers have a limit on the number of TCP ports.

To trigger a server-side event, we call the StartServerEvent method within an using block:

using (var access = _button.Document.StartServerEvent())
{
    // ...
    // code to modify the page
    // ...
}

The StartServerEvent method returns a ServerEvent disposable object. When the using block closes and disposes this variable, the changes made in the page are flushed to the client. It is also possible to flush any partial changes by calling the method FlushPartialChanges on the ServerEvent instance.

Example

The following is an example of a page that loads and, later on, a delayed background task modifies the page.

[LaraPage(Address = "/server")]
class ServerEventsPage : IPage
{
    readonly Button _button;

    public ServerEventsPage()
    {
        _button = new Button()
        {
            Disabled = true
        };
        _button.AppendText("before");
        System.Console.WriteLine("instance created");
    }

    public Task OnGet()
    {
        LaraUI.Page.JSBridge.ServerEventsOn();
        LaraUI.Page.Document.Body.AppendChild(_button);
        Task.Run(DelayedTask);
        return Task.CompletedTask;
    }

    private async void DelayedTask()
    {
        await Task.Delay(4000);
        using (var access = _button.Document.StartServerEvent())
        {
            _button.ClearChildren();
            _button.AppendText("after");
        }
    }
}
Clone this wiki locally