0
# Ktor Client WebSockets
1
2
Ktor Client WebSockets provides WebSocket client capabilities for iOS x64 (iOS simulator) applications using Kotlin Multiplatform. This plugin enables asynchronous bidirectional communication with WebSocket servers, offering coroutine-based APIs for connection management, message sending/receiving, and connection lifecycle handling.
3
4
## Package Information
5
6
- **Package Name**: ktor-client-websockets-iosx64
7
- **Package Type**: maven
8
- **Coordinates**: io.ktor:ktor-client-websockets-iosx64
9
- **Language**: Kotlin Multiplatform
10
- **Platform**: iOS x64 (iOS simulator)
11
- **Installation**: Add `implementation("io.ktor:ktor-client-websockets:3.2.0")` to your iOS x64 target dependencies (the iosX64 artifact is automatically resolved)
12
13
## Core Imports
14
15
```kotlin
16
import io.ktor.client.*
17
import io.ktor.client.plugins.websocket.*
18
import io.ktor.websocket.*
19
```
20
21
## Basic Usage
22
23
```kotlin
24
import io.ktor.client.*
25
import io.ktor.client.plugins.websocket.*
26
import io.ktor.websocket.*
27
28
// Create client with WebSocket support
29
val client = HttpClient {
30
install(WebSockets) {
31
pingInterval = 20.seconds
32
maxFrameSize = 1024 * 1024 // 1MB
33
}
34
}
35
36
// Connect and use WebSocket
37
client.webSocket("ws://echo.websocket.org") {
38
// Send text message
39
send("Hello WebSocket!")
40
41
// Receive and process messages
42
for (frame in incoming) {
43
when (frame) {
44
is Frame.Text -> {
45
val text = frame.readText()
46
println("Received: $text")
47
}
48
is Frame.Binary -> {
49
val bytes = frame.readBytes()
50
println("Received ${bytes.size} bytes")
51
}
52
is Frame.Close -> {
53
println("Connection closed")
54
break
55
}
56
else -> {}
57
}
58
}
59
}
60
61
client.close()
62
```
63
64
## Architecture
65
66
The Ktor Client WebSocket plugin is built around several key components:
67
68
- **Plugin Installation**: `WebSockets` plugin integrates with Ktor's client architecture
69
- **Session Management**: `ClientWebSocketSession` and `DefaultClientWebSocketSession` provide connection context
70
- **Connection Builders**: Multiple convenience functions (`webSocket`, `ws`, `wss`, `webSocketSession`) for different use cases
71
- **Frame Handling**: Direct access to WebSocket frames for low-level control
72
- **Serialization Support**: Built-in content converter support for object serialization
73
- **Configuration**: Ping intervals, max frame sizes, and extension support
74
75
## Capabilities
76
77
### Plugin Configuration
78
79
WebSocket plugin installation and configuration including ping intervals, frame size limits, content converters, and extension support.
80
81
```kotlin { .api }
82
fun HttpClientConfig<*>.WebSockets(config: WebSockets.Config.() -> Unit)
83
84
class WebSockets(
85
val pingIntervalMillis: Long,
86
val maxFrameSize: Long,
87
val contentConverter: WebsocketContentConverter? = null
88
)
89
90
class Config {
91
var pingInterval: Duration?
92
var maxFrameSize: Long
93
var contentConverter: WebsocketContentConverter?
94
fun extensions(block: WebSocketExtensionsConfig.() -> Unit)
95
}
96
```
97
98
[Plugin Configuration](./plugin-configuration.md)
99
100
### WebSocket Connections
101
102
Connection establishment functions providing flexible ways to connect to WebSocket servers with both high-level and low-level APIs.
103
104
```kotlin { .api }
105
suspend fun HttpClient.webSocket(
106
request: HttpRequestBuilder.() -> Unit,
107
block: suspend DefaultClientWebSocketSession.() -> Unit
108
)
109
110
suspend fun HttpClient.webSocket(
111
method: HttpMethod = HttpMethod.Get,
112
host: String? = null,
113
port: Int? = null,
114
path: String? = null,
115
request: HttpRequestBuilder.() -> Unit = {},
116
block: suspend DefaultClientWebSocketSession.() -> Unit
117
)
118
119
suspend fun HttpClient.wss(
120
request: HttpRequestBuilder.() -> Unit,
121
block: suspend DefaultClientWebSocketSession.() -> Unit
122
)
123
```
124
125
[WebSocket Connections](./websocket-connections.md)
126
127
### Session Management
128
129
WebSocket session types and lifecycle management for maintaining connection state and handling communication context.
130
131
```kotlin { .api }
132
interface ClientWebSocketSession : WebSocketSession {
133
val call: HttpClientCall
134
}
135
136
class DefaultClientWebSocketSession(
137
override val call: HttpClientCall,
138
delegate: DefaultWebSocketSession
139
) : ClientWebSocketSession, DefaultWebSocketSession by delegate
140
141
suspend fun HttpClient.webSocketSession(
142
block: HttpRequestBuilder.() -> Unit
143
): DefaultClientWebSocketSession
144
```
145
146
[Session Management](./session-management.md)
147
148
### Message Serialization
149
150
Content conversion support for serializing and deserializing objects to/from WebSocket frames with type safety.
151
152
```kotlin { .api }
153
suspend inline fun <reified T> DefaultClientWebSocketSession.sendSerialized(data: T)
154
155
suspend fun DefaultClientWebSocketSession.sendSerialized(data: Any?, typeInfo: TypeInfo)
156
157
suspend inline fun <reified T> DefaultClientWebSocketSession.receiveDeserialized(): T
158
159
suspend fun <T> DefaultClientWebSocketSession.receiveDeserialized(typeInfo: TypeInfo): T
160
161
val DefaultClientWebSocketSession.converter: WebsocketContentConverter?
162
```
163
164
[Message Serialization](./message-serialization.md)
165
166
## Types
167
168
### Core Types
169
170
```kotlin { .api }
171
data object WebSocketCapability : HttpClientEngineCapability<Unit>
172
173
data object WebSocketExtensionsCapability : HttpClientEngineCapability<Unit>
174
175
class WebSocketException(message: String, cause: Throwable?) : IllegalStateException(message, cause)
176
177
const val PINGER_DISABLED: Long = 0
178
179
interface WebsocketContentConverter
180
181
class WebsocketConverterNotFoundException(message: String) : Exception(message)
182
183
class WebsocketDeserializeException(message: String, val frame: Frame) : Exception(message)
184
```
185
186
## Error Handling
187
188
The plugin throws specific exceptions for different error conditions:
189
190
- `WebSocketException`: Handshake failures, connection errors, or protocol violations
191
- `WebsocketConverterNotFoundException`: When no content converter is available for serialization
192
- `WebsocketDeserializeException`: When frame deserialization fails
193
- Standard WebSocket exceptions from the underlying `io.ktor.websocket` package