Configuration¶
This guide explains the various configuration options available in SignalRKore. These options allow you to customize the behavior of the SignalR client to suit your needs.
HubConnectionBuilder¶
All configuration options are set through the HubConnectionBuilder when creating a connection:
val connection = HubConnectionBuilder.create("https://example.com/chathub") {
// Configuration options go here
}
Transport Options¶
Transport Type¶
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.
See the Transport API reference for more details.
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.
Authentication and Headers¶
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. It's equivalent to:
This is useful for JWT authentication.
Timeout and Reconnection¶
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:
Automatic Reconnect¶
You can configure automatic reconnection when the connection is lost:
See the Reconnection guide for more details on reconnection options.
HTTP Client¶
Custom HTTP Client¶
You can provide a custom Ktor HTTP client:
This is useful if you need to configure the HTTP client with custom settings or plugins.
Warning: If you provide a custom HTTP client, you must install all the necessary plugins. At a minimum, you need to install: -
WebSockets- Required for WebSockets transport -SSE- Required for Server-Sent Events transport -HttpTimeout- Required for timeout handlingFailure to install these plugins may result in runtime errors.
OkHttp Engine¶
If you're using the JVM or Android platform, you can configure the OkHttp engine:
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build()
httpClient = HttpClient(OkHttp) {
engine {
preconfigured = okHttpClient
}
install(WebSockets)
install(SSE)
install(HttpTimeout)
}
Protocol and Serialization¶
Protocol¶
You can specify the hub protocol:
Two protocols are available:
JsonHubProtocol(default) - JSON messages, part of the coresignalrkoreartifactMessagePackHubProtocol- binary MessagePack messages, in thesignalrkore-msgpackartifact
See the Protocol API reference for more details.
MessagePack¶
To use the MessagePack protocol, add the signalrkore-msgpack artifact:
and set the protocol:
The server has to enable it with AddMessagePackProtocol(). Keep in mind that:
- Server-Sent Events cannot carry binary data, so the connection uses WebSockets or Long Polling.
- Property names are case sensitive. Map Kotlin properties to PascalCase .NET properties with
@SerialName. - Enums are sent as strings,
ByteArrayas binary data andkotlin.time.Instantas a MessagePack timestamp, which .NET reads as aDateTime.
Payloads are encoded by the MessagePack format, which you can configure and pass to the protocol:
protocol = MessagePackHubProtocol(
messagePack = MessagePack {
ignoreUnknownKeys = true
encodeDefaults = true
serializersModule = SerializersModule {
contextual(UUID::class) { UUIDSerializer }
}
},
)
JSON Serialization¶
You can provide a custom JSON serializer for the arguments, stream items and results of the JSON protocol:
protocol = JsonHubProtocol(
json = Json {
ignoreUnknownKeys = true
isLenient = true
// Other configuration options
}
)
This is useful if you need to configure the JSON serializer with custom settings or modules. The negotiate and handshake responses of the server are always read by the library itself, so this Json instance only affects your payloads.
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.
For example, you can register custom serializers for specific types:
protocol = JsonHubProtocol(
json = Json {
ignoreUnknownKeys = true
serializersModule = SerializersModule {
contextual(Date::class) { DateSerializer }
contextual(UUID::class) { UUIDSerializer }
}
}
)
Logging¶
Custom 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)
}
}
Integration with Logging Frameworks¶
You can integrate with popular logging frameworks:
Timber (Android)¶
logger = Logger { severity, msg, err ->
when (severity) {
Logger.Severity.INFO -> Timber.tag("SignalR").i(err, msg())
Logger.Severity.WARNING -> Timber.tag("SignalR").w(err, msg())
Logger.Severity.ERROR -> Timber.tag("SignalR").e(err, msg())
}
}
Napier (Multiplatform)¶
logger = Logger { severity, msg, err ->
when (severity) {
Logger.Severity.INFO -> Napier.i(msg(), err, tag = "SignalR")
Logger.Severity.WARNING -> Napier.w(msg(), err, tag = "SignalR")
Logger.Severity.ERROR -> Napier.e(msg(), err, tag = "SignalR")
}
}
SLF4J (JVM)¶
val slf4j = LoggerFactory.getLogger("SignalR")
logger = Logger { severity, msg, err ->
when (severity) {
Logger.Severity.INFO -> slf4j.info(msg(), err)
Logger.Severity.WARNING -> slf4j.warn(msg(), err)
Logger.Severity.ERROR -> slf4j.error(msg(), err)
}
}
Complete Example¶
Here's a complete example that demonstrates all configuration options:
val connection = HubConnectionBuilder.create("https://example.com/chathub") {
// Transport options
transports = setOf(TransportEnum.WebSockets)
skipNegotiate = true
// Authentication and headers
headers = mapOf("Custom-Header" to "Value")
accessTokenProvider = { "your-access-token" }
// Timeout and reconnection
handshakeResponseTimeout = 30.seconds
serverTimeout = 30.seconds // default
keepAliveInterval = 15.seconds // default
automaticReconnect = AutomaticReconnect.exponentialBackoff()
// HTTP client
httpClient = HttpClient {
install(WebSockets)
install(SSE)
install(HttpTimeout)
}
// Protocol and serialization
protocol = JsonHubProtocol(
json = Json {
ignoreUnknownKeys = true
isLenient = true
}
)
// Logging
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)
}
}
}
Platform-Specific Configuration¶
Android¶
On Android, you might want to use the Android-specific HTTP client:
iOS¶
On iOS, you might want to use the Darwin-specific HTTP client:
Next Steps¶
Now that you know how to configure SignalRKore, you can learn how to:
- Send messages to the hub
- Receive messages from the hub
- Work with streams
- Configure automatic reconnection