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:
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:
Available transports:
TransportEnum.WebSocketsTransportEnum.ServerSentEventsTransportEnum.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:
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:
Available reconnect options:
AutomaticReconnect.Inactive(default): No automatic reconnectionAutomaticReconnect.Active: Basic reconnect policy (waits 0, 2, 10, and 30 seconds before each attempt)AutomaticReconnect.exponentialBackoff(): Exponential backoff policyAutomaticReconnect.Custom: Custom reconnect policy
See Reconnection for more details on reconnection options.
Handshake Response Timeout¶
You can configure the timeout for the handshake response:
Server Timeout¶
You can configure the maximum duration the connection will wait for a message from the server before closing:
Keep Alive Interval¶
You can configure how often the client sends keep-alive pings to the server:
HTTP Headers¶
You can add custom HTTP headers to the connection:
Access Token¶
You can provide an access token for authentication:
This is a convenience property that sets the "Authorization" header with a "Bearer" prefix.
HTTP Client¶
You can provide a custom Ktor HTTP client:
Note: If you provide a custom HTTP client, make sure it has the necessary plugins installed:
Protocol¶
You can specify a custom hub protocol:
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 |