0
# Connection Management
1
2
Functions for establishing and managing WebSocket connections with support for various URL formats, request configurations, and connection lifecycle management.
3
4
## Capabilities
5
6
### WebSocket Connection Functions
7
8
Establish WebSocket connections using different URL and configuration patterns.
9
10
```kotlin { .api }
11
/**
12
* Opens a block with DefaultClientWebSocketSession using request builder
13
*/
14
suspend fun HttpClient.webSocket(
15
request: HttpRequestBuilder.() -> Unit,
16
block: suspend DefaultClientWebSocketSession.() -> Unit
17
)
18
19
/**
20
* Opens a block with DefaultClientWebSocketSession using URL components
21
*/
22
suspend fun HttpClient.webSocket(
23
method: HttpMethod = HttpMethod.Get,
24
host: String? = null,
25
port: Int? = null,
26
path: String? = null,
27
request: HttpRequestBuilder.() -> Unit = {},
28
block: suspend DefaultClientWebSocketSession.() -> Unit
29
)
30
31
/**
32
* Opens a block with DefaultClientWebSocketSession using URL string
33
*/
34
suspend fun HttpClient.webSocket(
35
urlString: String,
36
request: HttpRequestBuilder.() -> Unit = {},
37
block: suspend DefaultClientWebSocketSession.() -> Unit
38
)
39
```
40
41
**Usage Examples:**
42
43
```kotlin
44
import io.ktor.client.*
45
import io.ktor.client.plugins.websocket.*
46
import io.ktor.websocket.*
47
48
val client = HttpClient {
49
install(WebSockets)
50
}
51
52
// Using request builder
53
client.webSocket({
54
url("ws://localhost:8080/websocket")
55
parameter("token", "abc123")
56
}) {
57
send("Hello WebSocket!")
58
59
for (frame in incoming) {
60
when (frame) {
61
is Frame.Text -> println("Received: ${frame.readText()}")
62
is Frame.Close -> break
63
else -> {}
64
}
65
}
66
}
67
68
// Using URL components
69
client.webSocket(
70
method = HttpMethod.Get,
71
host = "localhost",
72
port = 8080,
73
path = "/chat"
74
) {
75
send("Connected to chat")
76
// Handle messages...
77
}
78
79
// Using URL string
80
client.webSocket("ws://example.com/stream") {
81
// WebSocket logic here
82
}
83
```
84
85
### WebSocket Session Functions
86
87
Create persistent WebSocket sessions that can be managed independently.
88
89
```kotlin { .api }
90
/**
91
* Opens a DefaultClientWebSocketSession using request builder
92
*/
93
suspend fun HttpClient.webSocketSession(
94
block: HttpRequestBuilder.() -> Unit
95
): DefaultClientWebSocketSession
96
97
/**
98
* Opens a DefaultClientWebSocketSession using URL components
99
*/
100
suspend fun HttpClient.webSocketSession(
101
method: HttpMethod = HttpMethod.Get,
102
host: String? = null,
103
port: Int? = null,
104
path: String? = null,
105
block: HttpRequestBuilder.() -> Unit = {}
106
): DefaultClientWebSocketSession
107
108
/**
109
* Opens a DefaultClientWebSocketSession using URL string
110
*/
111
suspend fun HttpClient.webSocketSession(
112
urlString: String,
113
block: HttpRequestBuilder.() -> Unit = {}
114
): DefaultClientWebSocketSession
115
```
116
117
**Usage Examples:**
118
119
```kotlin
120
// Create and manage session manually
121
val session = client.webSocketSession("ws://localhost:8080/websocket")
122
123
try {
124
session.send("Hello!")
125
126
val response = session.incoming.receive()
127
if (response is Frame.Text) {
128
println("Server replied: ${response.readText()}")
129
}
130
} finally {
131
session.close()
132
}
133
134
// Session with custom headers
135
val authenticatedSession = client.webSocketSession {
136
url("ws://api.example.com/websocket")
137
header("Authorization", "Bearer $token")
138
}
139
```
140
141
### Short Alias Functions (ws)
142
143
Convenient aliases for WebSocket connection functions.
144
145
```kotlin { .api }
146
/**
147
* Alias for webSocket function with URL components
148
*/
149
suspend fun HttpClient.ws(
150
method: HttpMethod = HttpMethod.Get,
151
host: String? = null,
152
port: Int? = null,
153
path: String? = null,
154
request: HttpRequestBuilder.() -> Unit = {},
155
block: suspend DefaultClientWebSocketSession.() -> Unit
156
): Unit
157
158
/**
159
* Alias for webSocket function with request builder
160
*/
161
suspend fun HttpClient.ws(
162
request: HttpRequestBuilder.() -> Unit,
163
block: suspend DefaultClientWebSocketSession.() -> Unit
164
): Unit
165
166
/**
167
* Alias for webSocket function with URL string
168
*/
169
suspend fun HttpClient.ws(
170
urlString: String,
171
request: HttpRequestBuilder.() -> Unit = {},
172
block: suspend DefaultClientWebSocketSession.() -> Unit
173
): Unit
174
```
175
176
**Usage Examples:**
177
178
```kotlin
179
// Short aliases for convenience
180
client.ws("ws://localhost:8080/ws") {
181
send("Quick connection")
182
}
183
184
client.ws(host = "localhost", port = 8080, path = "/api/ws") {
185
// WebSocket operations
186
}
187
```
188
189
### Secure WebSocket Functions (wss)
190
191
Establish secure WebSocket connections over TLS/SSL.
192
193
```kotlin { .api }
194
/**
195
* Opens a block with secure DefaultClientWebSocketSession using request builder
196
*/
197
suspend fun HttpClient.wss(
198
request: HttpRequestBuilder.() -> Unit,
199
block: suspend DefaultClientWebSocketSession.() -> Unit
200
): Unit
201
202
/**
203
* Opens a block with secure DefaultClientWebSocketSession using URL string
204
*/
205
suspend fun HttpClient.wss(
206
urlString: String,
207
request: HttpRequestBuilder.() -> Unit = {},
208
block: suspend DefaultClientWebSocketSession.() -> Unit
209
): Unit
210
211
/**
212
* Opens a block with secure DefaultClientWebSocketSession using URL components
213
*/
214
suspend fun HttpClient.wss(
215
method: HttpMethod = HttpMethod.Get,
216
host: String? = null,
217
port: Int? = null,
218
path: String? = null,
219
request: HttpRequestBuilder.() -> Unit = {},
220
block: suspend DefaultClientWebSocketSession.() -> Unit
221
): Unit
222
```
223
224
**Usage Examples:**
225
226
```kotlin
227
// Secure WebSocket connection
228
client.wss("wss://secure.example.com/websocket") {
229
send("Secure connection established")
230
231
for (frame in incoming) {
232
when (frame) {
233
is Frame.Text -> {
234
val message = frame.readText()
235
println("Secure message: $message")
236
}
237
is Frame.Close -> break
238
else -> {}
239
}
240
}
241
}
242
243
// Secure connection with authentication
244
client.wss(
245
host = "api.example.com",
246
port = 443,
247
path = "/secure-ws"
248
) {
249
header("Authorization", "Bearer $secureToken")
250
} {
251
// Handle secure WebSocket communication
252
}
253
```
254
255
### URL Protocol Configuration
256
257
Automatic protocol handling for WebSocket connections.
258
259
**Protocol Mapping:**
260
- `ws://` - Standard WebSocket protocol (default port 80)
261
- `wss://` - Secure WebSocket protocol over TLS (default port 443)
262
- Automatic protocol upgrade from HTTP to WebSocket during connection handshake
263
264
**Usage Examples:**
265
266
```kotlin
267
// Protocol is automatically set based on function used
268
client.webSocket("ws://example.com/ws") { /* insecure */ }
269
client.wss("wss://example.com/ws") { /* secure */ }
270
271
// Manual protocol specification
272
client.webSocket {
273
url {
274
protocol = URLProtocol.WS // or URLProtocol.WSS
275
host = "example.com"
276
port = protocol.defaultPort
277
path("/websocket")
278
}
279
} {
280
// WebSocket operations
281
}
282
```
283
284
### Connection Lifecycle
285
286
WebSocket connections automatically handle the HTTP upgrade handshake and manage the connection lifecycle.
287
288
**Connection Process:**
289
1. HTTP request sent with WebSocket upgrade headers
290
2. Server responds with 101 Switching Protocols
291
3. Connection upgraded to WebSocket protocol
292
4. Session block executed with active WebSocket
293
5. Connection automatically closed when block completes
294
295
**Error Handling:**
296
297
```kotlin
298
try {
299
client.webSocket("ws://unreliable.example.com/ws") {
300
send("Test message")
301
// Connection operations
302
}
303
} catch (e: WebSocketException) {
304
println("WebSocket error: ${e.message}")
305
} catch (e: Exception) {
306
println("Connection error: ${e.message}")
307
}
308
```