1. Home
  2. Docs
  3. Documentation
  4. Plugins
  5. Client implementation

Client implementation

Next step is to use the SB Client to invoke methods on the server from a client application.

Add new project, and name it SB.Plugins.Demo.Client. The project needs to be runable, so select either console application or something else that can be started. For demo purposes, .NET Core console application is used.

Client dependencies are:

  • SB.Client NuGet package – this package contains the plumbing between the client and the server
  • SB.Plugins.Demo.Core – so that ICalculatorServer interface is available to the client
  • Microsoft.Extensions.Logging, and
  • Microsoft.Extensions.Logging.Console – to add log output

The first step is to configure the client, using Dependency Injection. Add a class named CalculatorDemo. The implementation of the class is made of three parts:

  • Constructor – where the configuration of the client happens
  • Event handlers – which are triggered on certain events
  • Run method – to start the connection

Configuration

The client is configured in the constructor. IServiceCollection is used to configure SB Client and other required services.

public CalculatorDemo(string endpoint)
{
    var services = new ServiceCollection();

    services.AddLogging(loggingBuilder =>
    {
        loggingBuilder.AddConsole();
    });

    services.AddSBClient();
    services.AddSBClientDefaultImpl();

    var provider = services.BuildServiceProvider();
    this.client = provider.GetService<IClient>();
    this.client.OnConnected += this.Client_OnConnected;
    this.client.OnFailedToConnect += this.Client_OnFailedToConnect;
    this.endpoint = endpoint;
}

Methods AddLogging, AddSBClient and AddSBClientDefaultImpl must be called. Logging is required for the internals to work, and other two methods configure the client.

It is also possible to add a plugin to the client (which will be invoked from the server) by using the IClient.AddPlugin<TPlugin>(TPlugin plugin) method. A client plugin is added in the Available server interfaces chapter, to demonstrate invocation of client methods from the server.

Event Handlers

IClient supports three event handlers:

  • OnConnected – fired when the client connects to the server
  • OnDisconnected – fired when the client disconnects from the server
  • OnFailedToConnect – fired when the client fails to connect to the server

This demo uses OnConnected and OnFailedToConnect. When the client is connected, methods are invoked on the server. More on that in the next chapter.

Run method

This method is called from the main program, and starts the connection using a generated username.

public void Run()
{
    string username = $"User_{new Random().Next()}";
    this.client.Connect(username, this.endpoint);
}

Next step: Remote method invocation.

Was this article helpful to you? Yes No

How can we help?