Skip to content

Client

Note

This applies to the latest version of the library. If you are still using version 0.x, please refer to the migration guide.

The library provides a TCP/UDP client that can be used to communicate with a server. This client automatically connects to the server and creates a channel instance when the connection is established. Connection drops are automatically handled and the client will attempt to reconnect using an exponential backoff strategy.

Clients use the same channel configuration as the listeners, but they require additional configuration.

IServiceCollection services = ...;

/*
this registers a default client with the default channel configuration
*/
services.AddChannelsClient( "tcp://example.host:8080" );

/*
we could also register the default client with a named channel configuration
*/
// services.AddChannelsClient( "channel1", "tcp://example.host:8080" );

/*
when we need to create a client, we only need to
inject the `IChannelsClientFactory` interface
*/
public class MyClient
{
    private readonly IChannelsClient client;

    public MyClient( IChannelsClientFactory factory )
    {
        client = factory.CreateClient();
    }

    public Task ExecuteAsync()
    {
        // ...
    }
}

If we need to configure multiple clients with different channel configurations, we can register them as named clients instead.

IServiceCollection services = ...;

/*
this registers a named client (client1) with the default channel configuration
*/
services.AddChannelsNamedClient( "client1", "tcp://example.host:8080" );

/*
this registers a named client (client2) with a named channel configuration (channel1)
*/
services.AddChannelsNamedClient( "client2", "channel1", "tcp://example.host:8080" );

// ...

public class MyClient
{
    private readonly IChannelsClient client1;

    public MyClient( IChannelsClientFactory factory )
    {
        client1 = factory.CreateClient( "client1" );
    }

    public Task ExecuteAsync()
    {
        // ...
    }
}

Note

Please note that channel name and client name are two different things. The channel name identifies the channel configuration, while the client name is used to identify a client instance.