Table of Contents

Interface ISessionFactory

Namespace
PushTechnology.ClientInterface.Client.Session
Assembly
Diffusion.Client.dll

The factory for client ISession instances.

public interface ISessionFactory

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" );

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(int) or MaximumMessageSize(int) 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 four non-blocking alternatives, OpenAsync(string) and OpenAsync(string, CancellationToken) that provide the result asynchronously using a Task, as well as, Open(string, ISessionOpenCallback) and Open<TContext>(string, TContext, ISessionOpenContextCallback<TContext>) that provide the result asynchronously using a callback.

The overloaded methods Open(), OpenAsync() or OpenAsync(CancellationToken) use the session factory attributes to locate a server rather than a URL. The server is identified by the ServerHost(string), ServerPort(int), RequestPath(string) and SecureTransport(bool) attributes.

If a URL is specified, it takes precedence over the serverHost, serverPort, requestPath, and secureTransport session factory attributes.


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.

Methods

CertificateValidation(CertificateValidationCallback)

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

ISessionFactory CertificateValidation(CertificateValidationCallback certificateValidationCallback)

Parameters

certificateValidationCallback CertificateValidationCallback

The callback to validate the remote certificate used for authentication.

Returns

ISessionFactory

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

Examples

Setting certificate validation to allow any remote certificate.

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

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.

ConnectionTimeout(int)

Sets the connection timeout.

ISessionFactory ConnectionTimeout(int millisecondsTimeout)

Parameters

millisecondsTimeout int

The default connection timeout in milliseconds.

Returns

ISessionFactory

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

Examples

Setting the connection timeout to 5 minutes.

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

Remarks

This constrains the time taken to establish an initial connection to the server. The WriteTimeout(int) 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.

Credentials(ICredentials)

Sets the credentials.

ISessionFactory Credentials(ICredentials credentials)

Parameters

credentials ICredentials

The credentials.

Returns

ISessionFactory

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

Examples

Setting the credentials that have been created with the ICredentialsFactory.

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

Remarks

The default is NoCredentials().


Added in 5.0.

Exceptions

ArgumentNullException

credentials is null.

See Also

CustomCredentials(byte[])

Sets credentials using an array of bytes.

ISessionFactory CustomCredentials(byte[] bytes)

Parameters

bytes byte[]

The credentials.

Returns

ISessionFactory

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

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 );

Remarks

The default is NoCredentials().


Added in 5.0.

Exceptions

ArgumentNullException

bytes is null.

See Also

HttpProxy(string, int)

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

ISessionFactory HttpProxy(string host, int port)

Parameters

host string

The host name of the HTTP proxy.

port int

The port of the HTTP proxy.

Returns

ISessionFactory

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

Examples

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

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

Remarks

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


Added in 5.1.

Exceptions

ArgumentNullException

host is null.

ArgumentOutOfRangeException

port is not a valid IP port range of System.Net.IPEndPoint.MinPort to System.Net.IPEndPoint.MaxPort".

HttpProxy(string, int, IHttpProxyAuthentication)

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

ISessionFactory HttpProxy(string host, int port, IHttpProxyAuthentication authentication)

Parameters

host string

The host name of the HTTP proxy.

port int

The port of the HTTP proxy.

authentication IHttpProxyAuthentication

The proxy authentication details.

Returns

ISessionFactory

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

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 );

Remarks

This is a variant of HttpProxy(string, int) 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.

Exceptions

ArgumentNullException

host, or authentication is null.

ArgumentOutOfRangeException

port is not a valid IP port range of System.Net.IPEndPoint.MinPort to System.Net.IPEndPoint.MaxPort.

InitialRetryStrategy(RetryStrategy)

Sets the initial retry strategy.

ISessionFactory InitialRetryStrategy(RetryStrategy strategy)

Parameters

strategy RetryStrategy

The retry strategy to use.

Returns

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(int)

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

ISessionFactory InputBufferSize(int sizeInBytes)

Parameters

sizeInBytes int

The input buffer size in bytes.

Returns

ISessionFactory

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

Examples

Setting the input buffer size to 10 MiB.

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

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(int) 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.

Exceptions

ArgumentOutOfRangeException

sizeInBytes is less than MAXIMUM_MESSAGE_SIZE_MIN.

LocalEndPoint(IPEndPoint)

Sets the optional local endpoint to bind to.

ISessionFactory LocalEndPoint(IPEndPoint endPoint)

Parameters

endPoint IPEndPoint

The local endpoint, or null.

Returns

ISessionFactory

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

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 );

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.

MaximumMessageSize(int)

Sets the maximum message size.

ISessionFactory MaximumMessageSize(int sizeInBytes)

Parameters

sizeInBytes int

The maximum message size in bytes.

Returns

ISessionFactory

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

Examples

Setting the maximum message size to 10 MiB.

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

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.

Exceptions

ArgumentOutOfRangeException

sizeInBytes is less than MAXIMUM_MESSAGE_SIZE_MIN.

MaximumQueueSize(int)

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

ISessionFactory MaximumQueueSize(int sizeInMessages)

Parameters

sizeInMessages int

The maximum number of messages that may be queued.

Returns

ISessionFactory

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

Examples

Setting the outbound message queue size to 5000 messages.

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

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.

Exceptions

ArgumentOutOfRangeException

sizeInMessages is less than 1.

NoCredentials()

Sets the credentials to NONE.

ISessionFactory NoCredentials()

Returns

ISessionFactory

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

Examples

Setting the credentials to NONE.

var factory = Diffusion.Sessions.NoCredentials();

Remarks

This is the default.


Added in 5.0.

See Also

NoReconnection()

Disables reconnection.

ISessionFactory NoReconnection()

Returns

ISessionFactory

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

Examples

Disabling reconnection.

var factory = Diffusion.Sessions.NoReconnection();

Remarks

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

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


Added in 5.5.

Open()

Open a connection to a server and request a new session.

ISession Open()

Returns

ISession

A new session instance.

Examples

Opening a session after the server location has been configured as above.

var session = Diffusion.Sessions.Open();

Remarks

Warning

This is a convenience version of OpenAsync() which blocks until the session has been established.

The server location is configured using the ServerHost(string), ServerPort(int), SecureTransport(bool) and RequestPath(string) methods.


Added in 6.12.

Exceptions

SessionEstablishmentException

If an initial connection could not be established.

Open(string)

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

ISession Open(string url)

Parameters

url string

The server URL.

Returns

ISession

A new session instance.

Examples

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

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

Remarks

This method is a variant of Open() that uses a URL to specify the server location, ignoring the ServerHost(string), ServerPort(int), RequestPath(string), SecureTransport(bool) session factory attributes.

Warning

This method will block until the session has been established.


Added in 5.0.

Exceptions

ArgumentNullException

If url is null.

SessionEstablishmentException

If an initial connection could not be established.

Open(string, ISessionOpenCallback)

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

[Obsolete("Deprecated since 6.12. Use ISessionFactory.OpenAsync instead. This method will be removed in a future release.")]
void Open(string url, ISessionOpenCallback callback)

Parameters

url string

The server URL.

callback ISessionOpenCallback

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

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 );

Remarks

This method is a variant of Open() that uses a URL to specify the server location, ignoring the ServerHost(string), ServerPort(int), RequestPath(string), SecureTransport(bool) session factory attributes.

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.

Caution

Deprecated since 6.12. Use the new OpenAsync() instead. This method will be removed in a future release.


Added in 5.3.

OpenAsync()

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

Task<ISession> OpenAsync()

Returns

Task<ISession>

A Task that completes when a response is received from the server. If a session was established, the Task will complete successfully with a ISession value. Otherwise, the Task will complete with an exception.

Examples

Opening a session after the server location has been configured as above.

var session = await Diffusion.Sessions.OpenAync();

Remarks

The server location is configured using the ServerHost(string), ServerPort(int), SecureTransport(bool) and RequestPath(string) methods.

This method is non-blocking. The result is provided asynchronously by the returned Task.

Added in 6.12.

Exceptions

SessionEstablishmentException

If an initial connection could not be established.

OpenAsync(string)

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

Task<ISession> OpenAsync(string url)

Parameters

url string

The server URL.

Returns

Task<ISession>

A Task that completes when a response is received from the server. If a session was established, the Task will complete successfully with a ISession value. Otherwise, the Task will complete with an exception.

Examples

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

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

Remarks

This method is non-blocking. The result is provided asynchronously by the returned Task.

This method is a variant of OpenAsync() that uses a URL to specify the server location, ignoring the ServerHost(string), ServerPort(int), RequestPath(string), SecureTransport(bool) session factory attributes.

Added in 6.12.

Exceptions

ArgumentNullException

If url is null.

SessionEstablishmentException

If an initial connection could not be established.

OpenAsync(string, CancellationToken)

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

Task<ISession> OpenAsync(string url, CancellationToken cancellationToken)

Parameters

url string

The server URL.

cancellationToken CancellationToken

The cancellation token used to cancel the current operation.

Returns

Task<ISession>

A Task that completes when a response is received from the server. If a session was established, the Task will complete successfully with a ISession value. Otherwise, the Task will complete with an exception.

Examples

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

var session = await Diffusion.Sessions.OpenAync( "ws://localhost:8080", cancellationSource.Token );

Remarks

This method is non-blocking. The result is provided asynchronously by the returned Task.

This method is a variant of OpenAsync(CancellationToken) that uses a URL to specify the server location, ignoring the ServerHost(string), ServerPort(int), RequestPath(string), SecureTransport(bool) session factory attributes.

Added in 6.12.

Exceptions

ArgumentNullException

If url is null.

SessionEstablishmentException

If an initial connection could not be established.

OpenAsync(CancellationToken)

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

Task<ISession> OpenAsync(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

The cancellation token used to cancel the current operation.

Returns

Task<ISession>

A Task that completes when a response is received from the server. If a session was established, the Task will complete successfully with a ISession value. Otherwise, the Task will complete with an exception.

Examples

Opening a session after the server location has been configured as above.

var session = await Diffusion.Sessions.OpenAync(cancellationSource.Token);

Remarks

The server location is configured using the ServerHost(string), ServerPort(int), SecureTransport(bool) and RequestPath(string) methods.

This method is non-blocking. The result is provided asynchronously by the returned Task.

Added in 6.12.

Exceptions

SessionEstablishmentException

If an initial connection could not be established.

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

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

[Obsolete("Deprecated since 6.12. Use ISessionFactory.OpenAsync instead. This method will be removed in a future release.")]
void Open<TContext>(string url, TContext context, ISessionOpenContextCallback<TContext> callback)

Parameters

url string

The server URL.

context TContext

The context to pass to the callback, or null.

callback ISessionOpenContextCallback<TContext>

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

Type Parameters

TContext

The context type.

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 );

Remarks

This method is a variant of Open() that uses a URL to specify the server location, ignoring the ServerHost(string), ServerPort(int), RequestPath(string), SecureTransport(bool) session factory attributes.

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

Caution

Deprecated since 6.12. Use the new OpenAsync() instead. This method will be removed in a future release.


Added in 5.3.

OutputBufferSize(int)

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

ISessionFactory OutputBufferSize(int sizeInBytes)

Parameters

sizeInBytes int

The output buffer size in bytes.

Returns

ISessionFactory

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

Examples

Setting the output buffer size to 10 MiB.

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

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(int) 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.

Exceptions

ArgumentOutOfRangeException

sizeInBytes is less than MAXIMUM_MESSAGE_SIZE_MIN.

Password(string)

Sets the credentials to PLAIN_PASSWORD.

ISessionFactory Password(string password)

Parameters

password string

The password.

Returns

ISessionFactory

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

Examples

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

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

Remarks

The default is NoCredentials().


Added in 5.0.

Exceptions

ArgumentNullException

password is null.

See Also

Principal(string)

Sets the security principal.

ISessionFactory Principal(string principal)

Parameters

principal string

The principal.

Returns

ISessionFactory

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

Examples

Setting a principal of "client".

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

Remarks

By default this will be anonymous (empty string).


Added in 5.0.

Exceptions

ArgumentNullException

principal is null.

Properties(IDictionary<string, string>)

Sets a user-defined session properties.

ISessionFactory Properties(IDictionary<string, string> properties)

Parameters

properties IDictionary<string, string>

The dictionary of user-defined session properties.

Returns

ISessionFactory

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

Examples

Setting session properties.

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

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.

Exceptions

ArgumentNullException

properties is null.

Property(string, string)

Sets a user-defined session property value.

ISessionFactory Property(string key, string value)

Parameters

key string

The property key.

value string

The property value.

Returns

ISessionFactory

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

Examples

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

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

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.

Exceptions

ArgumentNullException

key, or value is null.

ReconnectionStrategy(IReconnectionStrategy)

Sets the reconnection strategy.

ISessionFactory ReconnectionStrategy(IReconnectionStrategy reconnectionStrategy)

Parameters

reconnectionStrategy IReconnectionStrategy

The reconnection strategy to use, or null.

Returns

ISessionFactory

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

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 );

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.

ReconnectionTimeout(int)

Sets the reconnection timeout.

ISessionFactory ReconnectionTimeout(int millisecondsTimeout)

Parameters

millisecondsTimeout int

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

Returns

ISessionFactory

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

Examples

Setting the reconnection timeout to 5 minutes.

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

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.

RecoveryBufferSize(int)

Sets the recovery buffer size.

ISessionFactory RecoveryBufferSize(int sizeInMessages)

Parameters

sizeInMessages int

The recovery buffer size in messages.

Returns

ISessionFactory

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

Examples

Setting the recovery buffer size to 5000 messages.

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

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.

Exceptions

ArgumentOutOfRangeException

sizeInMessages is less than 0.

RequestPath(string)

Set the path used for HTTP requests.

ISessionFactory RequestPath(string requestPath)

Parameters

requestPath string

The path used for HTTP requests.

Returns

ISessionFactory

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

Examples

Setting the path for HTTP requests to "/path/diffusion".

var factory = Diffusion.Sessions.RequestPath( "/path/diffusion" );

Remarks

This value is only used if a URL is not provided when opening a session. The path must start with a '/' and end with '/diffusion'.

The default is DEFAULT_REQUEST_PATH.


Added in 6.12.

Exceptions

ArgumentNullException

requestPath is null.

ArgumentException

requestPath is invalid.

SecureTransport(bool)

Set if a secure transport should be used.

ISessionFactory SecureTransport(bool secureTransport)

Parameters

secureTransport bool

If transport layer security is enabled for the WebSocket transport.

Returns

ISessionFactory

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

Examples

Setting the secure transport to true.

var factory = Diffusion.Sessions.SecureTransport( true );

Remarks

This value is only used if a URL is not provided when opening a session. Enables or disables the use of transport layer security for the WebSocket transport. TLS is disabled by default because in most cases to correctly enable TLS an SSLContext must also be provided using SslContext(RemoteCertificateValidationCallback).


Added in 6.12.

ServerHost(string)

Set the host name of the server to connect the session to.

ISessionFactory ServerHost(string host)

Parameters

host string

The host name of the server.

Returns

ISessionFactory

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

Examples

Setting the server host to "host".

var factory = Diffusion.Sessions.ServerHost( "host" );

Remarks

This value is only used if a URL is not provided when opening a session.


Added in 6.12.

Exceptions

ArgumentNullException

host is null.

ServerPort(int)

Set the port of the server to connect the session to.

ISessionFactory ServerPort(int port)

Parameters

port int

The port of the server.

Returns

ISessionFactory

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

Examples

Setting the server port to 9000.

var factory = Diffusion.Sessions.ServerPort( 9000 );

Remarks

This value is only used if a URL is not provided when opening a session.

The provided value must be within the range used for port numbers.

---

Added in 6.12.

Exceptions

ArgumentException

port is invalid.

SessionErrorHandler(EventHandler<SessionErrorHandlerEventArgs>)

Nominates an error-handler for a session.

ISessionFactory SessionErrorHandler(EventHandler<SessionErrorHandlerEventArgs> errorHandler)

Parameters

errorHandler EventHandler<SessionErrorHandlerEventArgs>

The error-handler for the ErrorNotified event.

Returns

ISessionFactory

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

Examples

Register a delegate for the ErrorNotified event.

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

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.

SessionStateChangedHandler(EventHandler<SessionListenerEventArgs>)

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

ISessionFactory SessionStateChangedHandler(EventHandler<SessionListenerEventArgs> eventHandler)

Parameters

eventHandler EventHandler<SessionListenerEventArgs>

The event-handler for the StateChanged event.

Returns

ISessionFactory

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

Examples

Register a delegate for the StateChanged event.

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

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.

SslContext(RemoteCertificateValidationCallback)

Sets the SSL Context if a secure connection is required.

[Obsolete("This method will be removed in a future release. Use CertificateValidation instead.", false)]
ISessionFactory SslContext(RemoteCertificateValidationCallback remoteCertificateValidationCallback)

Parameters

remoteCertificateValidationCallback RemoteCertificateValidationCallback

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

Returns

ISessionFactory

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

Examples

Setting certificate validation to allow any remote certificate.

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

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.

WriteTimeout(int)

Sets the write timeout value for blocking writes.

ISessionFactory WriteTimeout(int millisecondsTimeout)

Parameters

millisecondsTimeout int

The write timeout in milliseconds.

Returns

ISessionFactory

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

Examples

Setting the write timeout to 5 minutes.

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

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.