Skip to content

HubConnectionBuilder

The HubConnectionBuilder class is used to create and configure instances of HubConnection. It provides a fluent API for setting various connection options.

Creating a Connection

The simplest way to create a connection is to use the create method:

val connection = HubConnectionBuilder.create("https://example.com/chathub")

Configuration Options

You can configure the connection by passing a lambda to the create method:

val connection = HubConnectionBuilder.create("https://example.com/chathub") {
    transports = setOf(TransportEnum.WebSockets)
    skipNegotiate = true
    automaticReconnect = AutomaticReconnect.Active
    handshakeResponseTimeout = 30.seconds
}

Transport

You can limit which transports the connection may use:

transports = setOf(TransportEnum.WebSockets, TransportEnum.LongPolling)

Available transports:

  • TransportEnum.WebSockets
  • TransportEnum.ServerSentEvents
  • TransportEnum.LongPolling

By default, all of them are allowed. The allowed transports are tried in the order the server offers them, and if one fails to start, the next one is tried. If none of them can be started, start throws TransportsFailedException with the error of each transport that was tried.

Skip Negotiate

You can skip the negotiate step when using WebSockets:

transports = setOf(TransportEnum.WebSockets)
skipNegotiate = true

Note: This option can only be used when WebSockets is the only allowed transport, and there is no transport fallback.

Automatic Reconnect

You can configure automatic reconnection when the connection is lost:

automaticReconnect = AutomaticReconnect.Active

Available reconnect options:

  • AutomaticReconnect.Inactive (default): No automatic reconnection
  • AutomaticReconnect.Active: Basic reconnect policy (waits 0, 2, 10, and 30 seconds before each attempt)
  • AutomaticReconnect.exponentialBackoff(): Exponential backoff policy
  • AutomaticReconnect.Custom: Custom reconnect policy

See Reconnection for more details on reconnection options.

Handshake Response Timeout

You can configure the timeout for the handshake response:

handshakeResponseTimeout = 30.seconds

Server Timeout

You can configure the maximum duration the connection will wait for a message from the server before closing:

serverTimeout = 30.seconds // default is 30 seconds

Keep Alive Interval

You can configure how often the client sends keep-alive pings to the server:

keepAliveInterval = 15.seconds // default is 15 seconds

HTTP Headers

You can add custom HTTP headers to the connection:

headers = mapOf(
    "Authorization" to "Bearer token",
    "Custom-Header" to "Value"
)

Access Token

You can provide an access token for authentication:

accessTokenProvider = { "your-access-token" }

This is a convenience property that sets the "Authorization" header with a "Bearer" prefix.

HTTP Client

You can provide a custom Ktor HTTP client:

httpClient = HttpClient(OkHttp) {
    engine {
        preconfigured = okHttpBuilder.build()
    }
}

Note: If you provide a custom HTTP client, make sure it has the necessary plugins installed:

HttpClient {
    install(WebSockets)
    install(SSE)
    install(HttpTimeout)
}

Protocol

You can specify a custom hub protocol:

protocol = JsonHubProtocol()

JSON Serialization

You can provide a custom JSON serializer for the payloads of the JSON protocol:

protocol = JsonHubProtocol(
    json = Json {
        ignoreUnknownKeys = true
        isLenient = true
        // Other configuration options
    }
)

By default the protocol ignores keys that your models don't declare, like the official SignalR clients. A custom Json replaces that default, so set ignoreUnknownKeys = true in it if you still want that.

Logger

You can provide a custom logger:

logger = Logger { severity, msg, err ->
    when (severity) {
        Logger.Severity.INFO -> Log.i("SignalR", msg(), err)
        Logger.Severity.WARNING -> Log.w("SignalR", msg(), err)
        Logger.Severity.ERROR -> Log.e("SignalR", msg(), err)
    }
}

Complete Example

Here's a complete example that demonstrates all configuration options:

val connection = HubConnectionBuilder.create("https://example.com/chathub") {
    transports = setOf(TransportEnum.WebSockets)
    skipNegotiate = true
    automaticReconnect = AutomaticReconnect.Active
    handshakeResponseTimeout = 30.seconds
    serverTimeout = 30.seconds // default
    keepAliveInterval = 15.seconds // default
    headers = mapOf("Custom-Header" to "Value")
    accessTokenProvider = { "your-access-token" }
    httpClient = HttpClient {
        install(WebSockets)
        install(SSE)
        install(HttpTimeout)
    }
    protocol = JsonHubProtocol(
        json = Json {
            ignoreUnknownKeys = true
            isLenient = true
        }
    )
    logger = Logger { severity, msg, err ->
        when (severity) {
            Logger.Severity.INFO -> Log.i("SignalR", msg(), err)
            Logger.Severity.WARNING -> Log.w("SignalR", msg(), err)
            Logger.Severity.ERROR -> Log.e("SignalR", msg(), err)
        }
    }
}

API Reference

Methods

Name Parameters Return Type Description
create url: String, configure: (HttpHubConnectionBuilder.() -> Unit)? = null HubConnection Creates a new HubConnection with the specified URL and configuration

HttpHubConnectionBuilder Properties

Name Type Default Description
transports Set<TransportEnum> all transports The transports the connection may use
skipNegotiate Boolean false Whether to skip the negotiate step (WebSockets only)
automaticReconnect AutomaticReconnect AutomaticReconnect.Inactive The automatic reconnect policy
handshakeResponseTimeout Duration 15.seconds The timeout for the handshake response
serverTimeout Duration 30.seconds The maximum time to wait for a message from the server before closing the connection
keepAliveInterval Duration 15.seconds The interval at which keep-alive pings are sent to the server
headers Map<String, String> emptyMap() HTTP headers to include in requests
accessTokenProvider (suspend () -> String)? null Access token for authentication (sets the "Authorization" header with "Bearer" prefix)
httpClient HttpClient? null Custom Ktor HTTP client
protocol HubProtocol JsonHubProtocol() The protocol used for communication with the hub
logger Logger Logger.Empty Logger for logging messages