Interface ISessionFactory

The factory for client ISession instances.

Namespace: PushTechnology.ClientInterface.Client.Session
Assembly: Diffusion.Client.dll
Syntax
public interface ISessionFactory
Remarks

Each instance is immutable, and has a number of session attributes that determine how sessions should be established. An initial instance of this factory with default values for all attributes can be obtained from Sessions. Methods such as InputBufferSize(Int32) or MaximumMessageSize(Int32) that allow attributes to be changed do not modify this instance. Each method returns a copy of this factory, with a single changed attribute.


Establishing a session

A new session can be created using Open(String) specifying a URL that identifies the server. This is a blocking method that waits for a session to be established before returning.

There are two non-blocking alternatives, Open(String, ISessionOpenCallback) and Open<TContext>(String, TContext, ISessionOpenContextCallback<TContext>) that provide the result asynchronously using a callback.


URL format

URLs should take the form scheme://host:port, where scheme is chosen from the following table and determines the transport protocol used to send Diffusion messages.

Scheme Transport Protocol
ws WebSocket. See https://tools.ietf.org/html/rfc6455 (RFC 6455).
wss WebSocket over TLS.

TLS is Transport Layer Security, commonly known as SSL. TLS-based protocols use cryptography to provide transport-level privacy, authentication, and integrity, and protects against network-sniffing and man-in-the-middle attacks.

Tip

We recommend using the TLS variants for all communication. For a typical application, you should only consider not using TLS for unauthenticated ("anonymous") client sessions.


Note

This interface does not require user implementation and is only used to hide implementation details.

Added in 5.0.

Examples

An instance of this factory can be obtained by calling Sessions.

var factory = Diffusion.Sessions;

A minimal example of establishing a session with principal "client" and password "password" connecting to localhost with the ws transport protocol on port 8080.

var session = Diffusion.Sessions
    .Principal( "client" )
    .Password( "password" )
    .Open( "ws://localhost:8080" );

Methods

CertificateValidation(CertificateValidationCallback)

Sets the certificate validation callback for Secure Sockets Layer (SSL) authentication.

Declaration
ISessionFactory CertificateValidation(CertificateValidationCallback certificateValidationCallback)
Parameters
Type Name Description
CertificateValidationCallback certificateValidationCallback

The callback to validate the remote certificate used for authentication.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the certificate validation callback changed.

Remarks

The authentication is handled by the Security Support Provider (SSPI) channel provider. By setting a callback the session is able to control validation of the server's certificate and handle any errors SSPI encountered during authentication.

If the callback is not set the default behaviour is to REJECT the remote certificate on any errors during authentication.

Setting the callback will not enable transport layer security. It must also be specified by the URL.


Added in 6.4.

Examples

Setting certificate validation to allow any remote certificate.

var factory = Diffusion.Sessions
    .CertificateValidation( (certificate, chain, errors) => CertificateValidationResult.ACCEPT );

ConnectionTimeout(Int32)

Sets the connection timeout.

Declaration
ISessionFactory ConnectionTimeout(int millisecondsTimeout)
Parameters
Type Name Description
System.Int32 millisecondsTimeout

The default connection timeout in milliseconds.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the connection timeout changed.

Remarks

This constrains the time taken to establish an initial connection to the server. The WriteTimeout(Int32) constrains the time to send the connection request. The server is responsible for limiting the overall time taken to complete a connection once it has received the request.

The default is DEFAULT_CONNECTION_TIMEOUT.

Warning

If millisecondsTimeout exceeds one hour (3600000ms), a warning will be logged and the time-out will be set to one hour. This is also the case for 'infinite' timeouts of 0 or any negative number.


Added in 5.0.

Examples

Setting the connection timeout to 5 minutes.

var factory = Diffusion.Sessions.ConnectionTimeout( 300_000 );

Credentials(ICredentials)

Sets the credentials.

Declaration
ISessionFactory Credentials(ICredentials credentials)
Parameters
Type Name Description
ICredentials credentials

The credentials.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the credentials changed.

Remarks

The default is NoCredentials().


Added in 5.0.

Examples

Setting the credentials that have been created with the ICredentialsFactory.

var credentials = Diffusion.Credentials.Password( "password" );
var factory = Diffusion.Sessions.Credentials( credentials );
See Also
ICredentialsFactory

CustomCredentials(Byte[])

Sets credentials using an array of bytes.

Declaration
ISessionFactory CustomCredentials(byte[] bytes)
Parameters
Type Name Description
System.Byte[] bytes

The credentials.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the credentials changed.

Remarks

The default is NoCredentials().


Added in 5.0.

Examples

Setting the credentials to CUSTOM with a plain text UTF-8 encoded byte array.

var bytes = Encoding.UTF8.GetBytes( "password" );
var factory = Diffusion.Sessions.CustomCredentials( bytes );
See Also
Custom(Byte[])

HttpProxy(String, Int32)

Sets the address of the HTTP Proxy that should be used to make connections to the server.

Declaration
ISessionFactory HttpProxy(string host, int port)
Parameters
Type Name Description
System.String host

The host name of the HTTP proxy.

System.Int32 port

The port of the HTTP proxy.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory that will use the provided HTTP proxy.

Remarks

This allows connection to a server using HTTP CONNECT tunnelling through the specified proxy.


Added in 5.1.

Examples

Setting a HTTP Proxy with host "localhost" and port 9090.

var factory = Diffusion.Sessions.HttpProxy( "localhost", 9090 );

HttpProxy(String, Int32, IHttpProxyAuthentication)

Sets the address of the HTTP Proxy that should be used to make connections to the server.

Declaration
ISessionFactory HttpProxy(string host, int port, IHttpProxyAuthentication authentication)
Parameters
Type Name Description
System.String host

The host name of the HTTP proxy.

System.Int32 port

The port of the HTTP proxy.

IHttpProxyAuthentication authentication

The proxy authentication details.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory that will use the provided HTTP proxy.

Remarks

This is a variant of HttpProxy(String, Int32) that provides authentication details to the HTTP proxy.

This allows connection to a server using HTTP CONNECT tunnelling through the specified proxy, with authentication.

The given authentication only affects communication with the proxy, it is not passed on to the server. ProxyAuthentication can be used to create a suitable instance.

The Principal(String) and Credentials(ICredentials) methods control authentication with the server and do not affect proxy authentication.


Added in 5.1.

Examples

Setting a HTTP Proxy with host "localhost", port 9090, and HTTP BASIC authentication with a username "joe" and password "s3cret".

var authentication = Diffusion.ProxyAuthentication.Basic( "joe", "s3cret" );
var factory = Diffusion.Sessions.HttpProxy( "localhost", 9090, authentication );

InitialRetryStrategy(RetryStrategy)

Sets the initial retry strategy.

Declaration
ISessionFactory InitialRetryStrategy(RetryStrategy strategy)
Parameters
Type Name Description
RetryStrategy strategy

The retry strategy to use.

Returns
Type Description
ISessionFactory

A new immutable instance of the factory with the initial retry strategy changed.

Remarks

The strategy will determine whether a failure to open a session due to a SessionEstablishmentTransientException should be retried and, if so, at what interval and for how many attempts.

If no initial retry strategy is set there will be no attempt to retry after such a failure.


Added in 6.9.

InputBufferSize(Int32)

Sets the input buffer size for socket connection buffers and message receiving buffers.

Declaration
ISessionFactory InputBufferSize(int sizeInBytes)
Parameters
Type Name Description
System.Int32 sizeInBytes

The input buffer size in bytes.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the input buffer size changed.

Remarks

This controls both how much pending data the socket can accommodate and how much available data will be read by the input tasks. In general setting both this and OutputBufferSize(Int32) to the same reasonable size will result in higher network throughput. The cost of the receiving buffer is only incurred when reading data for processing. The cost of the socket buffer is always incurred and may be modified by the operating system.

The given sizeInBytes must not be less than MAXIMUM_MESSAGE_SIZE_MIN.

The default is DEFAULT_INPUT_BUFFER_SIZE.


Added in 5.0.

Examples

Setting the input buffer size to 10 MiB.

var factory = Diffusion.Sessions.InputBufferSize( 10_000_000 );

LocalEndPoint(IPEndPoint)

Sets the optional local endpoint to bind to.

Declaration
ISessionFactory LocalEndPoint(IPEndPoint endPoint)
Parameters
Type Name Description
IPEndPoint endPoint

The local endpoint, or null.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the local endpoint changed.

Remarks

If you do not care which local address is assigned, you can create an System.Net.IPEndPoint using System.Net.IPAddress.Any as the address parameter, and the underlying service provider will assign the most appropriate network address. If you do not care which local port is used, you can create an System.Net.IPEndPoint using 0 for the port number. In this case, the service provider will assign an available port number between 1024 and 5000.

If the given endPoint is null, no local endpoint will be used.

By default no local endpoint is used.


Added in 6.4.

Examples

Setting the local endpoint with System.Net.IPAddress.Any and port 0.

var endpoint = new IPEndPoint( IPAddress.Any, 0 );
var factory = Diffusion.Sessions.LocalEndPoint( endpoint );

MaximumMessageSize(Int32)

Sets the maximum message size.

Declaration
ISessionFactory MaximumMessageSize(int sizeInBytes)
Parameters
Type Name Description
System.Int32 sizeInBytes

The maximum message size in bytes.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the maximum message size changed.

Remarks

This constrains the size of messages that will be accepted from the server and thus the size of any content that can be received. The limit is simply to protect against unexpectedly large messages.

The given sizeInBytes must not be less than MAXIMUM_MESSAGE_SIZE_MIN.

By default, the size of received messages is unconstrained – see DEFAULT_MAXIMUM_MESSAGE_SIZE.


Added in 5.0.

Examples

Setting the maximum message size to 10 MiB.

var factory = Diffusion.Sessions.MaximumMessageSize( 10_000_000 );

MaximumQueueSize(Int32)

Sets the maximum size of the outbound message queue for the connection.

Declaration
ISessionFactory MaximumQueueSize(int sizeInMessages)
Parameters
Type Name Description
System.Int32 sizeInMessages

The maximum number of messages that may be queued.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the maximum queue size changed.

Remarks

The outbound message queue should be large enough to accommodate all the messages sent to the server. This would include topic updates, messages sent using IMessaging and service requests such as registering a handler.

It may be necessary to increase this value for applications that send messages in bursts, or continue to send messages when a session is disconnected and reconnecting. Larger values allow more messages to be queued, and increase the memory footprint of the session.

If the outbound message queue fills, sending a message will cause the session to close with an error.

The default is DEFAULT_MAXIMUM_QUEUE_SIZE.

The queue must be able to hold at least a single message.


Added in 5.9.

Examples

Setting the outbound message queue size to 5000 messages.

var factory = Diffusion.Sessions.MaximumQueueSize( 5000 );

NoCredentials()

Sets the credentials to NONE.

Declaration
ISessionFactory NoCredentials()
Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the credentials changed.

Remarks

This is the default.


Added in 5.0.

Examples

Setting the credentials to NONE.

var factory = Diffusion.Sessions.NoCredentials();
See Also
NoCredentials()

NoReconnection()

Disables reconnection.

Declaration
ISessionFactory NoReconnection()
Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the reconnection feature disabled.

Remarks

The sessions will not attempt to reconnect in the event of unexpected connection loss.

This is equivalent to calling ReconnectionTimeout(Int32) with a timeout of 0.


Added in 5.5.

Examples

Disabling reconnection.

var factory = Diffusion.Sessions.NoReconnection();

Open(String)

Opens a connection to a server and requests a new client session.

Declaration
ISession Open(string url)
Parameters
Type Name Description
System.String url

The server URL.

Returns
Type Description
ISession

A new session instance.

Remarks

Warning

This method will block until the session has been established.


Added in 5.0.

Examples

Opening a session to localhost using the WebSocket protocol on port 8080.

var session = Diffusion.Sessions.Open( "ws://localhost:8080" );

Open(String, ISessionOpenCallback)

Opens a connection to a server and requests a new client session.

Declaration
void Open(string url, ISessionOpenCallback callback)
Parameters
Type Name Description
System.String url

The server URL.

ISessionOpenCallback callback

The callback to notify of the result of attempting to open the session.

Remarks

This method is a callback-based variant of Open(String). It will return immediately. The result of the attempt to open the session will be notified to the given callback.


Added in 5.3.

Examples

The open callback.

class SessionOpenCallback : ISessionOpenCallback {
    public void OnError( ErrorReason errorReason ) {
        // TODO: Handle session open error in here.
    }

    public void OnOpened( ISession session ) {
        // TODO: Handle opened session in here.
    }
}

Opening a session with callback to localhost using the WebSocket protocol on port 8080.

var callback = new SessionOpenCallback();
Diffusion.Sessions.Open( "ws://localhost:8080", callback );

Open<TContext>(String, TContext, ISessionOpenContextCallback<TContext>)

Opens a connection to a server and requests a new client session.

Declaration
void Open<TContext>(string url, TContext context, ISessionOpenContextCallback<TContext> callback)
Parameters
Type Name Description
System.String url

The server URL.

TContext context

The context to pass to the callback, or null.

ISessionOpenContextCallback<TContext> callback

The callback to notify of the result of attempting to open the session.

Type Parameters
Name Description
TContext

The context type.

Remarks

This is the same as Open(String, ISessionOpenCallback) but with the addition of an arbitrary context object.


Added in 5.3.

Examples

The open callback with a context of type System.Int32.

class SessionOpenCallback : ISessionOpenContextCallback<int> {
    public void OnError( int context, ErrorReason errorReason ) {
        // TODO: Handle session open error in here.
    }

    public void OnOpened( int context, ISession session ) {
        // TODO: Handle opened session in here.
    }
}

Opening a session with callback to localhost using the WebSocket protocol on port 8080 and a context of 42.

var callback = new SessionOpenCallback();
Diffusion.Sessions.Open( "ws://localhost:8080", 42, callback );

OutputBufferSize(Int32)

Sets the output buffer size for socket connection buffers and message sending buffers.

Declaration
ISessionFactory OutputBufferSize(int sizeInBytes)
Parameters
Type Name Description
System.Int32 sizeInBytes

The output buffer size in bytes.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the output buffer size changed.

Remarks

This controls both how much pending data the socket can accommodate and how much data will be batched by sending messages. In general setting both this and InputBufferSize(Int32) to the same reasonable size will result in higher network throughput. The cost of the sending buffer is only incurred when queuing data for output. The cost of the socket buffer is always incurred and may be modified by the operating system.

The given sizeInBytes must not be less than MAXIMUM_MESSAGE_SIZE_MIN.

The default is DEFAULT_OUTPUT_BUFFER_SIZE.


Added in 5.0.

Examples

Setting the output buffer size to 10 MiB.

var factory = Diffusion.Sessions.OutputBufferSize( 10_000_000 );

Password(String)

Sets the credentials to PLAIN_PASSWORD.

Declaration
ISessionFactory Password(string password)
Parameters
Type Name Description
System.String password

The password.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the credentials changed.

Remarks

The default is NoCredentials().


Added in 5.0.

Examples

Setting the credentials to PLAIN_PASSWORD with the password "password".

var factory = Diffusion.Sessions.Password( "password" );
See Also
Password(String)

Principal(String)

Sets the security principal.

Declaration
ISessionFactory Principal(string principal)
Parameters
Type Name Description
System.String principal

The principal.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the principal changed.

Remarks

By default this will be anonymous (empty string).


Added in 5.0.

Examples

Setting a principal of "client".

var factory = Diffusion.Sessions.Principal( "client" );

Properties(IDictionary<String, String>)

Sets a user-defined session properties.

Declaration
ISessionFactory Properties(IDictionary<string, string> properties)
Parameters
Type Name Description
IDictionary<System.String, System.String> properties

The dictionary of user-defined session properties.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the supplied properties set.

Remarks

Supplied session properties will be provided to the server when a session is created using this session factory. The supplied properties will be validated during authentication and may be discarded or changed.

The specified properties will be added to any existing properties set for this session factory. If any of the keys have been previously declared, they will be overwritten with the new values.

For details of how session properties are used see ISession.


Added in 6.2.

Examples

Setting session properties.

var properties = new Dictionary<string, string> {
    {  "one", "1" },
    { "two", "2" },
};
var factory = Diffusion.Sessions.Properties( properties );

Property(String, String)

Sets a user-defined session property value.

Declaration
ISessionFactory Property(string key, string value)
Parameters
Type Name Description
System.String key

The property key.

System.String value

The property value.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the named property set.

Remarks

Supplied session properties will be provided to the server when a session is created using this session factory. The supplied properties will be validated during authentication and may be discarded or changed.

The specified property will be added to any existing properties set for this session factory.

If the given key was already set, it will be overwritten.

For details of how session properties are used see ISession.


Added in 6.2.

Examples

Setting a session property with key "some key" and value "some value".

var factory = Diffusion.Sessions.Property( "some key", "some value" );

ReconnectionStrategy(IReconnectionStrategy)

Sets the reconnection strategy.

Declaration
ISessionFactory ReconnectionStrategy(IReconnectionStrategy reconnectionStrategy)
Parameters
Type Name Description
IReconnectionStrategy reconnectionStrategy

The reconnection strategy to use, or null.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the reconnection strategy changed.

Remarks

If reconnection is enabled, the given reconnectionStrategy will be called in the event of an unexpected connection loss.

If the reconnection timeout has been set, but not a strategy, sessions will use a default strategy that attempts to reconnect on a regular basis of 5 seconds until the reconnection timeout is exceeded.


Added in 5.5.

Examples

A reconnection strategy that waits for 2 minutes before reconnecting.

class ReconnectionStrategy : IReconnectionStrategy {
    public async Task PerformReconnection( IReconnectionAttempt reconnectionAttempt ) {
        var delay = TimeSpan.FromMinutes( 2 );
        await Task.Delay( delay ).ConfigureAwait( false );
        reconnectionAttempt.Start();
    }
}

Setting the reconnection strategy.

var strategy = new ReconnectionStrategy();
var factory = Diffusion.Sessions.ReconnectionStrategy( strategy );

ReconnectionTimeout(Int32)

Sets the reconnection timeout.

Declaration
ISessionFactory ReconnectionTimeout(int millisecondsTimeout)
Parameters
Type Name Description
System.Int32 millisecondsTimeout

The timeout duration to use when attempting to reconnect, in milliseconds.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the reconnection timeout changed.

Remarks

This determines the duration that sessions will attempt to reconnect for, in the event of unexpected connection loss.

The default is DEFAULT_RECONNECTION_TIMEOUT.

A timeout value of 0 or less is equivalent to calling NoReconnection().


Added in 5.5.

Examples

Setting the reconnection timeout to 5 minutes.

var factory = Diffusion.Sessions.ReconnectionTimeout( 300_000 );

RecoveryBufferSize(Int32)

Sets the recovery buffer size.

Declaration
ISessionFactory RecoveryBufferSize(int sizeInMessages)
Parameters
Type Name Description
System.Int32 sizeInMessages

The recovery buffer size in messages.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the recovery buffer size changed.

Remarks

If the server is configured to support reconnection, a session established with a non-zero reconnection time retains a buffer of sent messages. If the session disconnects and reconnects, this buffer is used to re-send messages that the server has not received.

The default is DEFAULT_RECOVERY_BUFFER_SIZE. Higher values increase the chance of successful reconnection, but increase the per-session memory footprint.

A buffer size of 0 will disable the recovery buffer.


Added in 6.0.

Examples

Setting the recovery buffer size to 5000 messages.

var factory = Diffusion.Sessions.RecoveryBufferSize( 5000 );

SessionErrorHandler(EventHandler<SessionErrorHandlerEventArgs>)

Nominates an error-handler for a session.

Declaration
ISessionFactory SessionErrorHandler(EventHandler<SessionErrorHandlerEventArgs> errorHandler)
Parameters
Type Name Description
EventHandler<SessionErrorHandlerEventArgs> errorHandler

The error-handler for the ErrorNotified event.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the error-handler changed.

Remarks

Subscribes the given errorHandler delegate to the ErrorNotified event for subsequent sessions that are created.

This method will replace any previously provided errorHandler.


Added in 5.0.

Examples

Register a delegate for the ErrorNotified event.

var factory = Diffusion.Sessions.SessionErrorHandler( ( sender, e ) => {
    // TODO: Act on error in here.
} );

SessionStateChangedHandler(EventHandler<SessionListenerEventArgs>)

Nominates an event-handler for session events from a session.

Declaration
ISessionFactory SessionStateChangedHandler(EventHandler<SessionListenerEventArgs> eventHandler)
Parameters
Type Name Description
EventHandler<SessionListenerEventArgs> eventHandler

The event-handler for the StateChanged event.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the event-handler changed.

Remarks

Subscribes the given eventHandler delegate to the StateChanged event for subsequent sessions that are created.

This method will replace any previously provided eventHandler.


Added in 5.0.

Examples

Register a delegate for the StateChanged event.

var factory = Diffusion.Sessions.SessionStateChangedHandler( (sender, e) => {
    // TODO: Act on changed state in here.
} );

SslContext(RemoteCertificateValidationCallback)

Sets the SSL Context if a secure connection is required.

Declaration
ISessionFactory SslContext(RemoteCertificateValidationCallback remoteCertificateValidationCallback)
Parameters
Type Name Description
RemoteCertificateValidationCallback remoteCertificateValidationCallback

The delegate responsible for validating the certificate supplied by the Diffusion server. Can be null.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the SSL context changed.

Remarks

If not explicitly supplied, the default System.Net.Security.SslStream System.Net.Security.RemoteCertificateValidationCallback will be used.

Setting the SSL Context will not enable transport layer security. It must also be specified by the URL.

Caution

Deprecated since 6.4. This method will be removed in a future release. Use CertificateValidation(CertificateValidationCallback) instead.


Added in 5.0.

Examples

Setting certificate validation to allow any remote certificate.

var factory = Diffusion.Sessions.SslContext( (sender, certificate, chain, errors) => true );

WriteTimeout(Int32)

Sets the write timeout value for blocking writes.

Declaration
ISessionFactory WriteTimeout(int millisecondsTimeout)
Parameters
Type Name Description
System.Int32 millisecondsTimeout

The write timeout in milliseconds.

Returns
Type Description
ISessionFactory

A new immutable instance of this factory with the write timeout changed.

Remarks

Blocking writes are only used for the initial connection request. If it is not possible to complete the write within this time, the connection is closed.

The default is DEFAULT_WRITE_TIMEOUT.

Warning

If millisecondsTimeout exceeds one hour (3600000ms), a warning will be logged and the time-out will be set to one hour. This is also the case for 'infinite' timeouts of 0 or any negative number.


Added in 5.0.

Examples

Setting the write timeout to 5 minutes.

var factory = Diffusion.Sessions.WriteTimeout( 300_000 );
Back to top