Ktor client WebSocket plugin for Windows x64 platform providing native WebSocket communication capabilities
npx @tessl/cli install tessl/maven-io-ktor--ktor-client-websockets-mingwx64@2.3.00
# Ktor Client WebSockets (MinGW x64)
1
2
Ktor Client WebSockets provides WebSocket client functionality for the Ktor framework, specifically compiled for Windows x64 using the MinGW toolchain. This plugin enables asynchronous WebSocket communication in Kotlin Multiplatform applications targeting native Windows applications.
3
4
## Package Information
5
6
- **Package Name**: io.ktor:ktor-client-websockets-mingwx64
7
- **Package Type**: maven
8
- **Language**: Kotlin
9
- **Platform**: mingwX64 (Windows x64 MinGW)
10
- **Installation**: Add to `build.gradle.kts` dependencies
11
12
```kotlin
13
dependencies {
14
implementation("io.ktor:ktor-client-websockets-mingwx64:2.3.13")
15
}
16
```
17
18
## Core Imports
19
20
```kotlin
21
import io.ktor.client.*
22
import io.ktor.client.plugins.websocket.*
23
import io.ktor.websocket.*
24
```
25
26
For engine-specific functionality (requires additional dependencies):
27
```kotlin
28
import io.ktor.client.engine.cio.*
29
```
30
31
For serialization support:
32
```kotlin
33
import io.ktor.serialization.*
34
```
35
36
## Basic Usage
37
38
```kotlin
39
import io.ktor.client.*
40
import io.ktor.client.engine.cio.*
41
import io.ktor.client.plugins.websocket.*
42
import io.ktor.websocket.*
43
44
val client = HttpClient(CIO) {
45
install(WebSockets) {
46
pingInterval = 20_000
47
maxFrameSize = Long.MAX_VALUE
48
}
49
}
50
51
// Connect to WebSocket server
52
client.webSocket(
53
method = HttpMethod.Get,
54
host = "echo.websocket.org",
55
port = 80,
56
path = "/"
57
) {
58
// Send text message
59
send("Hello WebSocket!")
60
61
// Receive and process messages
62
for (frame in incoming) {
63
when (frame) {
64
is Frame.Text -> {
65
val message = frame.readText()
66
println("Received: $message")
67
}
68
is Frame.Binary -> {
69
println("Received binary data")
70
}
71
is Frame.Close -> {
72
println("Connection closed")
73
break
74
}
75
else -> {}
76
}
77
}
78
}
79
80
client.close()
81
```
82
83
## Architecture
84
85
The Ktor WebSocket client is built around several key components:
86
87
- **WebSockets Plugin**: Core plugin providing WebSocket support with configuration options
88
- **Session Types**: Managed session interfaces with automatic ping-pong handling
89
- **Extension Functions**: Convenient builder functions for establishing WebSocket connections
90
- **Serialization Support**: Optional content conversion for structured data
91
- **Engine Integration**: Platform-specific WebSocket implementations through HTTP client engines
92
93
**Note**: Raw WebSocket sessions (without automatic ping-pong handling) require additional engine-specific dependencies like `ktor-client-cio` and are not included in this core WebSocket client package.
94
95
## Capabilities
96
97
### Plugin Installation and Configuration
98
99
Core WebSocket plugin setup with customizable connection parameters and extensions support.
100
101
```kotlin { .api }
102
fun HttpClientConfig<*>.WebSockets(config: WebSockets.Config.() -> Unit)
103
104
class WebSockets.Config {
105
var pingInterval: Long
106
var maxFrameSize: Long
107
var contentConverter: WebsocketContentConverter?
108
fun extensions(block: WebSocketExtensionsConfig.() -> Unit)
109
}
110
```
111
112
The WebSockets plugin must be installed on the HttpClient to enable WebSocket functionality. Configuration options include:
113
114
- `pingInterval`: Interval between ping frames in milliseconds (-1L to disable)
115
- `maxFrameSize`: Maximum frame size in bytes (default: Long.MAX_VALUE)
116
- `contentConverter`: Optional converter for serialization/deserialization
117
- `extensions`: Configuration block for WebSocket extensions
118
119
```kotlin
120
val client = HttpClient(CIO) {
121
install(WebSockets) {
122
pingInterval = 30_000 // Send ping every 30 seconds
123
maxFrameSize = 16 * 1024 * 1024 // 16MB max frame size
124
contentConverter = KotlinxWebsocketSerializationConverter(Json)
125
extensions {
126
// Configure WebSocket extensions
127
}
128
}
129
}
130
```
131
132
### WebSocket Connection Management
133
134
Managed WebSocket sessions with automatic ping-pong handling and connection lifecycle management.
135
136
```kotlin { .api }
137
suspend fun HttpClient.webSocketSession(
138
block: HttpRequestBuilder.() -> Unit
139
): DefaultClientWebSocketSession
140
141
suspend fun HttpClient.webSocketSession(
142
method: HttpMethod = HttpMethod.Get,
143
host: String? = null,
144
port: Int? = null,
145
path: String? = null,
146
block: HttpRequestBuilder.() -> Unit = {}
147
): DefaultClientWebSocketSession
148
149
suspend fun HttpClient.webSocketSession(
150
urlString: String,
151
block: HttpRequestBuilder.() -> Unit = {}
152
): DefaultClientWebSocketSession
153
154
suspend fun HttpClient.webSocket(
155
request: HttpRequestBuilder.() -> Unit,
156
block: suspend DefaultClientWebSocketSession.() -> Unit
157
)
158
159
suspend fun HttpClient.webSocket(
160
method: HttpMethod = HttpMethod.Get,
161
host: String? = null,
162
port: Int? = null,
163
path: String? = null,
164
request: HttpRequestBuilder.() -> Unit = {},
165
block: suspend DefaultClientWebSocketSession.() -> Unit
166
)
167
168
suspend fun HttpClient.webSocket(
169
urlString: String,
170
request: HttpRequestBuilder.() -> Unit = {},
171
block: suspend DefaultClientWebSocketSession.() -> Unit
172
)
173
174
interface ClientWebSocketSession : WebSocketSession {
175
val call: HttpClientCall
176
}
177
178
class DefaultClientWebSocketSession(
179
call: HttpClientCall,
180
delegate: DefaultWebSocketSession
181
) : ClientWebSocketSession, DefaultWebSocketSession
182
```
183
184
The WebSocket connection functions provide different ways to establish and manage WebSocket connections:
185
186
- `webSocketSession()`: Returns a session object for manual management
187
- `webSocket()`: Executes a block with automatic session cleanup
188
189
Example establishing a session:
190
```kotlin
191
val session = client.webSocketSession(
192
method = HttpMethod.Get,
193
host = "localhost",
194
port = 8080,
195
path = "/websocket"
196
) {
197
header("Authorization", "Bearer token")
198
}
199
200
// Use session...
201
session.close()
202
```
203
204
Example with automatic cleanup:
205
```kotlin
206
client.webSocket("wss://api.example.com/stream") {
207
send("subscribe:user-events")
208
209
for (frame in incoming) {
210
if (frame is Frame.Text) {
211
val data = frame.readText()
212
handleMessage(data)
213
}
214
}
215
} // Session automatically closed
216
```
217
218
### Secure WebSocket Connections
219
220
Secure WebSocket (WSS) support for encrypted connections using SSL/TLS.
221
222
```kotlin { .api }
223
suspend fun HttpClient.wss(
224
request: HttpRequestBuilder.() -> Unit,
225
block: suspend DefaultClientWebSocketSession.() -> Unit
226
)
227
228
suspend fun HttpClient.wss(
229
urlString: String,
230
request: HttpRequestBuilder.() -> Unit = {},
231
block: suspend DefaultClientWebSocketSession.() -> Unit
232
)
233
234
suspend fun HttpClient.wss(
235
method: HttpMethod = HttpMethod.Get,
236
host: String? = null,
237
port: Int? = null,
238
path: String? = null,
239
request: HttpRequestBuilder.() -> Unit = {},
240
block: suspend DefaultClientWebSocketSession.() -> Unit
241
)
242
```
243
244
Secure WebSocket functions automatically use WSS protocol and default to port 443:
245
246
```kotlin
247
client.wss(
248
host = "secure.example.com",
249
path = "/websocket"
250
) {
251
send("Hello secure WebSocket!")
252
253
val response = incoming.receive()
254
if (response is Frame.Text) {
255
println("Secure response: ${response.readText()}")
256
}
257
}
258
```
259
260
### Convenience Functions
261
262
Shorthand functions for common WebSocket operations.
263
264
```kotlin { .api }
265
suspend fun HttpClient.ws(
266
method: HttpMethod = HttpMethod.Get,
267
host: String? = null,
268
port: Int? = null,
269
path: String? = null,
270
request: HttpRequestBuilder.() -> Unit = {},
271
block: suspend DefaultClientWebSocketSession.() -> Unit
272
)
273
274
suspend fun HttpClient.ws(
275
request: HttpRequestBuilder.() -> Unit,
276
block: suspend DefaultClientWebSocketSession.() -> Unit
277
)
278
279
suspend fun HttpClient.ws(
280
urlString: String,
281
request: HttpRequestBuilder.() -> Unit = {},
282
block: suspend DefaultClientWebSocketSession.() -> Unit
283
)
284
```
285
286
The `ws()` functions are shortcuts for `webSocket()` functions:
287
288
```kotlin
289
// These are equivalent:
290
client.ws("ws://localhost:8080/echo") { /* ... */ }
291
client.webSocket("ws://localhost:8080/echo") { /* ... */ }
292
```
293
294
295
### Content Serialization
296
297
Structured data serialization and deserialization for WebSocket messages.
298
299
```kotlin { .api }
300
val DefaultClientWebSocketSession.converter: WebsocketContentConverter?
301
302
suspend fun DefaultClientWebSocketSession.sendSerialized(
303
data: Any?,
304
typeInfo: TypeInfo
305
)
306
307
suspend inline fun <reified T> DefaultClientWebSocketSession.sendSerialized(
308
data: T
309
)
310
311
suspend fun <T> DefaultClientWebSocketSession.receiveDeserialized(
312
typeInfo: TypeInfo
313
): T
314
315
suspend inline fun <reified T> DefaultClientWebSocketSession.receiveDeserialized(): T
316
317
interface WebsocketContentConverter {
318
// Converter implementation details
319
}
320
```
321
322
Content serialization requires a configured `contentConverter` in the WebSockets plugin:
323
324
```kotlin
325
@Serializable
326
data class ChatMessage(val user: String, val text: String, val timestamp: Long)
327
328
val client = HttpClient(CIO) {
329
install(WebSockets) {
330
contentConverter = KotlinxWebsocketSerializationConverter(Json)
331
}
332
}
333
334
client.webSocket("ws://chat.example.com") {
335
// Send structured data
336
sendSerialized(ChatMessage("alice", "Hello!", System.currentTimeMillis()))
337
338
// Receive structured data
339
val message = receiveDeserialized<ChatMessage>()
340
println("${message.user}: ${message.text}")
341
}
342
```
343
344
### Exception Handling
345
346
WebSocket-specific exceptions for error handling and connection management.
347
348
```kotlin { .api }
349
class WebSocketException(
350
message: String,
351
cause: Throwable? = null
352
) : IllegalStateException
353
354
class WebsocketConverterNotFoundException(
355
message: String,
356
cause: Throwable? = null
357
) : WebsocketContentConvertException
358
359
class WebsocketDeserializeException(
360
message: String,
361
cause: Throwable? = null,
362
val frame: Frame
363
) : WebsocketContentConvertException
364
365
open class WebsocketContentConvertException(
366
message: String,
367
cause: Throwable? = null
368
) : ContentConvertException
369
```
370
371
Common exception scenarios:
372
373
```kotlin
374
try {
375
client.webSocket("ws://unreachable.example.com") {
376
send("test")
377
}
378
} catch (e: WebSocketException) {
379
println("WebSocket error: ${e.message}")
380
} catch (e: ConnectTimeoutException) {
381
println("Connection timeout")
382
}
383
384
try {
385
val data = receiveDeserialized<MyData>()
386
} catch (e: WebsocketConverterNotFoundException) {
387
println("No converter configured for serialization")
388
} catch (e: WebsocketDeserializeException) {
389
println("Failed to deserialize message: ${e.message}")
390
println("Frame type: ${e.frame?.frameType}")
391
}
392
```
393
394
### Engine Capabilities
395
396
WebSocket engine capability detection and platform-specific features.
397
398
```kotlin { .api }
399
object WebSocketCapability : HttpClientEngineCapability<Unit>
400
401
object WebSocketExtensionsCapability : HttpClientEngineCapability<Unit>
402
```
403
404
Capability checking for engine compatibility:
405
406
```kotlin
407
val client = HttpClient(CIO)
408
409
// Check if engine supports WebSockets
410
val supportsWebSockets = client.engine.supportedCapabilities
411
.contains(WebSocketCapability)
412
413
// Check if engine supports WebSocket extensions
414
val supportsExtensions = client.engine.supportedCapabilities
415
.contains(WebSocketExtensionsCapability)
416
417
if (supportsWebSockets) {
418
// Proceed with WebSocket operations
419
} else {
420
throw IllegalStateException("Engine does not support WebSockets")
421
}
422
```
423
424
## Platform-Specific Notes
425
426
### MinGW x64 Compatibility
427
428
This package is specifically compiled for Windows x64 using the MinGW toolchain, providing:
429
430
- Native performance for Windows applications
431
- Full compatibility with Kotlin/Native Windows targets
432
- Integration with Windows-specific networking APIs
433
- Support for all standard WebSocket features without platform limitations
434
435
### Engine Support
436
437
The WebSocket client works with different Ktor engines on MinGW x64:
438
439
- **CIO**: Full WebSocket support with standard session capabilities
440
- **WinHttp**: Windows-native WebSocket implementation optimized for MinGW
441
442
For MinGW x64 target, both CIO and WinHttp engines provide WebSocket functionality. Raw WebSocket sessions require additional engine-specific extensions not included in this core package.
443
444
## Error Handling
445
446
Common error scenarios and handling patterns:
447
448
### Connection Errors
449
```kotlin
450
try {
451
client.webSocket("ws://invalid-host") { /* ... */ }
452
} catch (e: UnresolvedAddressException) {
453
// Handle DNS resolution failure
454
} catch (e: ConnectException) {
455
// Handle connection refused
456
} catch (e: WebSocketException) {
457
// Handle WebSocket protocol errors
458
}
459
```
460
461
### Protocol Errors
462
```kotlin
463
client.webSocket("ws://echo.websocket.org") {
464
try {
465
send("Hello")
466
val frame = incoming.receive()
467
// Process frame
468
} catch (e: ClosedReceiveChannelException) {
469
// Connection closed by peer
470
} catch (e: CancellationException) {
471
// Operation cancelled
472
}
473
}
474
```
475
476
### Serialization Errors
477
```kotlin
478
try {
479
val data = receiveDeserialized<MyType>()
480
} catch (e: WebsocketConverterNotFoundException) {
481
// No content converter configured
482
} catch (e: WebsocketDeserializeException) {
483
// Failed to deserialize - check frame type
484
when (e.frame?.frameType) {
485
FrameType.TEXT -> // Handle text frame error
486
FrameType.BINARY -> // Handle binary frame error
487
else -> // Handle other frame types
488
}
489
}
490
```