0
# Ktor Client WebSockets
1
2
Ktor Client WebSockets is a multiplatform WebSocket client plugin for the Ktor HTTP client. It enables applications to establish and manage WebSocket connections with full bidirectional communication capabilities, automatic ping-pong heartbeat, configurable frame limits, and cross-platform compatibility across JVM, JavaScript, iOS x64, Android, and other Kotlin Multiplatform targets.
3
4
## Package Information
5
6
- **Package Name**: ktor-client-websockets
7
- **Package Type**: maven
8
- **Language**: Kotlin
9
- **Installation**: `implementation("io.ktor:ktor-client-websockets:2.3.13")`
10
11
## Core Imports
12
13
```kotlin
14
import io.ktor.client.*
15
import io.ktor.client.plugins.websocket.*
16
import io.ktor.websocket.*
17
```
18
19
## Basic Usage
20
21
```kotlin
22
import io.ktor.client.*
23
import io.ktor.client.engine.cio.*
24
import io.ktor.client.plugins.websocket.*
25
import io.ktor.websocket.*
26
27
// Create client with WebSocket plugin
28
val client = HttpClient(CIO) {
29
install(WebSockets) {
30
pingInterval = 20_000 // 20 seconds
31
maxFrameSize = 1024 * 1024 // 1MB
32
}
33
}
34
35
// Connect to WebSocket and exchange messages
36
client.webSocket(
37
method = HttpMethod.Get,
38
host = "ws.postman-echo.com",
39
port = 443,
40
path = "/raw"
41
) {
42
// Send text frame
43
send("Hello WebSocket!")
44
45
// Receive frame
46
val frame = incoming.receive()
47
if (frame is Frame.Text) {
48
println("Received: ${frame.readText()}")
49
}
50
51
// Close connection
52
close(CloseReason(CloseReason.Codes.NORMAL, "Goodbye"))
53
}
54
55
client.close()
56
```
57
58
## Architecture
59
60
Ktor Client WebSockets is built around several key components:
61
62
- **WebSockets Plugin**: Main plugin that integrates with Ktor's HTTP client pipeline for WebSocket connections
63
- **Session Management**: Client-specific WebSocket sessions with HTTP call context and plugin configuration
64
- **Frame Processing**: Automatic handling of WebSocket frames including text, binary, ping, pong, and close frames
65
- **Content Serialization**: Integration with Ktor's content negotiation system for automatic serialization/deserialization
66
- **Platform Abstractions**: Platform-specific implementations for different Kotlin Multiplatform targets
67
- **Connection Management**: Automatic WebSocket handshake, connection lifecycle, and graceful termination
68
69
## Capabilities
70
71
### Plugin Installation and Configuration
72
73
WebSocket plugin installation and configuration for HttpClient with customizable ping intervals, frame size limits, and content conversion.
74
75
```kotlin { .api }
76
fun HttpClientConfig<*>.WebSockets(config: WebSockets.Config.() -> Unit)
77
78
class WebSockets internal constructor(
79
val pingInterval: Long,
80
val maxFrameSize: Long,
81
private val extensionsConfig: WebSocketExtensionsConfig,
82
val contentConverter: WebsocketContentConverter? = null
83
) {
84
class Config {
85
var pingInterval: Long = -1L
86
var maxFrameSize: Long = Int.MAX_VALUE.toLong()
87
var contentConverter: WebsocketContentConverter? = null
88
89
fun extensions(block: WebSocketExtensionsConfig.() -> Unit)
90
}
91
92
companion object Plugin : HttpClientPlugin<Config, WebSockets>
93
}
94
```
95
96
[Plugin Configuration](./plugin-configuration.md)
97
98
### WebSocket Connection Management
99
100
Core WebSocket connection establishment and session management functionality with support for different connection patterns and secure connections.
101
102
```kotlin { .api }
103
suspend fun HttpClient.webSocket(
104
method: HttpMethod = HttpMethod.Get,
105
host: String? = null,
106
port: Int? = null,
107
path: String? = null,
108
request: HttpRequestBuilder.() -> Unit = {},
109
block: suspend DefaultClientWebSocketSession.() -> Unit
110
)
111
112
suspend fun HttpClient.webSocketSession(
113
method: HttpMethod = HttpMethod.Get,
114
host: String? = null,
115
port: Int? = null,
116
path: String? = null,
117
block: HttpRequestBuilder.() -> Unit = {}
118
): DefaultClientWebSocketSession
119
120
suspend fun HttpClient.ws(
121
method: HttpMethod = HttpMethod.Get,
122
host: String? = null,
123
port: Int? = null,
124
path: String? = null,
125
request: HttpRequestBuilder.() -> Unit = {},
126
block: suspend DefaultClientWebSocketSession.() -> Unit
127
)
128
129
suspend fun HttpClient.wss(
130
method: HttpMethod = HttpMethod.Get,
131
host: String? = null,
132
port: Int? = null,
133
path: String? = null,
134
request: HttpRequestBuilder.() -> Unit = {},
135
block: suspend DefaultClientWebSocketSession.() -> Unit
136
)
137
```
138
139
[WebSocket Connections](./websocket-connections.md)
140
141
### WebSocket Session Operations
142
143
Client WebSocket session interfaces and operations for frame communication, session management, and HTTP call context access.
144
145
```kotlin { .api }
146
interface ClientWebSocketSession : WebSocketSession {
147
val call: HttpClientCall
148
}
149
150
class DefaultClientWebSocketSession(
151
override val call: HttpClientCall,
152
delegate: DefaultWebSocketSession
153
) : ClientWebSocketSession, DefaultWebSocketSession by delegate
154
155
val DefaultClientWebSocketSession.converter: WebsocketContentConverter?
156
```
157
158
[Session Operations](./session-operations.md)
159
160
### Content Serialization
161
162
WebSocket content serialization and deserialization functionality using Ktor's content conversion system for automatic object transformation.
163
164
```kotlin { .api }
165
suspend fun DefaultClientWebSocketSession.sendSerialized(
166
data: Any?,
167
typeInfo: TypeInfo
168
)
169
170
suspend inline fun <reified T> DefaultClientWebSocketSession.sendSerialized(
171
data: T
172
)
173
174
suspend fun <T> DefaultClientWebSocketSession.receiveDeserialized(
175
typeInfo: TypeInfo
176
): T
177
178
suspend inline fun <reified T> DefaultClientWebSocketSession.receiveDeserialized(): T
179
```
180
181
[Content Serialization](./content-serialization.md)
182
183
### Low-Level WebSocket Operations (CIO Engine)
184
185
CIO engine-specific raw WebSocket operations that bypass automatic ping-pong processing and provide direct frame access.
186
187
```kotlin { .api }
188
suspend fun HttpClient.webSocketRawSession(
189
method: HttpMethod = HttpMethod.Get,
190
host: String? = null,
191
port: Int? = null,
192
path: String? = null,
193
block: HttpRequestBuilder.() -> Unit = {}
194
): ClientWebSocketSession
195
196
suspend fun HttpClient.webSocketRaw(
197
method: HttpMethod = HttpMethod.Get,
198
host: String? = null,
199
port: Int? = null,
200
path: String? = null,
201
request: HttpRequestBuilder.() -> Unit = {},
202
block: suspend ClientWebSocketSession.() -> Unit
203
)
204
205
suspend fun HttpClient.wsRaw(
206
method: HttpMethod = HttpMethod.Get,
207
host: String? = null,
208
port: Int? = null,
209
path: String? = null,
210
request: HttpRequestBuilder.() -> Unit = {},
211
block: suspend ClientWebSocketSession.() -> Unit
212
)
213
214
suspend fun HttpClient.wssRaw(
215
method: HttpMethod = HttpMethod.Get,
216
host: String? = null,
217
port: Int? = null,
218
path: String? = null,
219
request: HttpRequestBuilder.() -> Unit = {},
220
block: suspend ClientWebSocketSession.() -> Unit
221
)
222
```
223
224
[Raw WebSocket Operations](./raw-websocket-operations.md)
225
226
## Core Types
227
228
```kotlin { .api }
229
// Engine Capabilities
230
object WebSocketCapability : HttpClientEngineCapability<Unit>
231
object WebSocketExtensionsCapability : HttpClientEngineCapability<Unit>
232
233
// Exceptions
234
class WebSocketException(message: String, cause: Throwable? = null) : IllegalStateException
235
236
// WebSocket Frame Types (from ktor-websockets)
237
enum class FrameType(val controlFrame: Boolean, val opcode: Int) {
238
TEXT(false, 1),
239
BINARY(false, 2),
240
CLOSE(true, 8),
241
PING(true, 9),
242
PONG(true, 0xa)
243
}
244
245
sealed class Frame {
246
class Text(val fin: Boolean, val data: ByteArray) : Frame
247
class Binary(val fin: Boolean, val data: ByteArray) : Frame
248
class Close(val reason: CloseReason) : Frame
249
class Ping(val data: ByteArray) : Frame
250
class Pong(val data: ByteArray) : Frame
251
}
252
253
data class CloseReason(val code: Short, val message: String) {
254
enum class Codes(val code: Short) {
255
NORMAL(1000),
256
GOING_AWAY(1001),
257
PROTOCOL_ERROR(1002),
258
CANNOT_ACCEPT(1003),
259
NOT_CONSISTENT(1007),
260
VIOLATED_POLICY(1008),
261
TOO_BIG(1009),
262
NO_EXTENSION(1010),
263
INTERNAL_ERROR(1011),
264
SERVICE_RESTART(1012),
265
TRY_AGAIN_LATER(1013)
266
}
267
}
268
269
// WebSocket Session Interfaces (from ktor-websockets)
270
interface WebSocketSession : CoroutineScope {
271
var masking: Boolean
272
var maxFrameSize: Long
273
val incoming: ReceiveChannel<Frame>
274
val outgoing: SendChannel<Frame>
275
val extensions: List<WebSocketExtension<*>>
276
277
suspend fun send(frame: Frame)
278
suspend fun flush()
279
}
280
281
interface DefaultWebSocketSession : WebSocketSession {
282
var pingIntervalMillis: Long
283
var timeoutMillis: Long
284
val closeReason: Deferred<CloseReason?>
285
}
286
```