0
# Session Management
1
2
WebSocket session types and lifecycle management for maintaining connection state and handling communication context.
3
4
## Capabilities
5
6
### Session Types
7
8
Core interfaces and classes for managing WebSocket sessions.
9
10
```kotlin { .api }
11
/**
12
* Client-specific WebSocket session interface extending base WebSocketSession
13
* with client call context
14
*/
15
interface ClientWebSocketSession : WebSocketSession {
16
/** HttpClientCall associated with this WebSocket session */
17
val call: HttpClientCall
18
}
19
20
/**
21
* Default implementation of client WebSocket session combining
22
* ClientWebSocketSession interface with DefaultWebSocketSession behavior
23
* @param call The associated HTTP client call
24
* @param delegate The underlying default WebSocket session
25
*/
26
class DefaultClientWebSocketSession(
27
override val call: HttpClientCall,
28
delegate: DefaultWebSocketSession
29
) : ClientWebSocketSession, DefaultWebSocketSession by delegate
30
```
31
32
### Session Creation Functions
33
34
Functions that return WebSocket sessions directly for manual lifecycle management.
35
36
```kotlin { .api }
37
/**
38
* Creates and returns a WebSocket session using request builder configuration
39
* @param block Configuration block for the HTTP request
40
* @return DefaultClientWebSocketSession for manual management
41
*/
42
suspend fun HttpClient.webSocketSession(
43
block: HttpRequestBuilder.() -> Unit
44
): DefaultClientWebSocketSession
45
46
/**
47
* Creates and returns a WebSocket session using method, host, port, and path
48
* @param method HTTP method for the WebSocket handshake (default: GET)
49
* @param host Target hostname
50
* @param port Target port number
51
* @param path Target path
52
* @param block Additional request configuration
53
* @return DefaultClientWebSocketSession for manual management
54
*/
55
suspend fun HttpClient.webSocketSession(
56
method: HttpMethod = HttpMethod.Get,
57
host: String? = null,
58
port: Int? = null,
59
path: String? = null,
60
block: HttpRequestBuilder.() -> Unit = {}
61
): DefaultClientWebSocketSession
62
63
/**
64
* Creates and returns a WebSocket session using URL string
65
* @param urlString WebSocket URL (ws:// or wss://)
66
* @param block Additional request configuration
67
* @return DefaultClientWebSocketSession for manual management
68
*/
69
suspend fun HttpClient.webSocketSession(
70
urlString: String,
71
block: HttpRequestBuilder.() -> Unit = {}
72
): DefaultClientWebSocketSession
73
```
74
75
**Usage Examples:**
76
77
```kotlin
78
// Create session with manual lifecycle management
79
val session = client.webSocketSession("ws://echo.websocket.org")
80
81
try {
82
// Use the session
83
session.send("Hello!")
84
85
val frame = session.incoming.receive()
86
when (frame) {
87
is Frame.Text -> println("Received: ${frame.readText()}")
88
else -> {}
89
}
90
} finally {
91
// Manual cleanup required
92
session.close()
93
}
94
95
// Create session with request configuration
96
val session = client.webSocketSession {
97
url("ws://example.com/ws")
98
header("Authorization", "Bearer token")
99
}
100
101
// Use session...
102
session.close()
103
```
104
105
### Session Properties and Context
106
107
Access to connection context and metadata through session properties.
108
109
```kotlin { .api }
110
/**
111
* Access to the HTTP client call associated with the WebSocket session
112
* Provides request/response context and metadata
113
*/
114
val ClientWebSocketSession.call: HttpClientCall
115
```
116
117
**Usage Examples:**
118
119
```kotlin
120
client.webSocket("ws://example.com") {
121
// Access call information
122
println("Connected to: ${call.request.url}")
123
println("Response status: ${call.response.status}")
124
println("Response headers: ${call.response.headers}")
125
126
// Access client information
127
println("Client engine: ${call.client.engine}")
128
129
// Send messages using session context
130
send("Hello from ${call.request.url.host}!")
131
}
132
```
133
134
## Session Lifecycle
135
136
### Automatic vs Manual Management
137
138
**Automatic Management (Recommended):**
139
140
```kotlin
141
// Connection and cleanup handled automatically
142
client.webSocket("ws://example.com") {
143
// Session is active here
144
send("Message")
145
// Session is automatically closed when block exits
146
}
147
```
148
149
**Manual Management:**
150
151
```kotlin
152
// Manual lifecycle control
153
val session = client.webSocketSession("ws://example.com")
154
try {
155
session.send("Message")
156
// Handle messages...
157
} finally {
158
session.close() // Must close manually
159
}
160
```
161
162
### Session State Management
163
164
WebSocket sessions inherit full functionality from `DefaultWebSocketSession`:
165
166
```kotlin
167
client.webSocket("ws://example.com") {
168
// Connection state
169
println("Is closed: ${closeReason.isActive}")
170
171
// Frame size configuration
172
maxFrameSize = 1024 * 1024 // 1MB
173
174
// Ping configuration
175
pingIntervalMillis = 30000 // 30 seconds
176
177
// Send different frame types
178
send("Text message")
179
send(Frame.Binary(true, byteArrayOf(1, 2, 3)))
180
send(Frame.Ping(byteArrayOf()))
181
182
// Receive frames
183
for (frame in incoming) {
184
when (frame) {
185
is Frame.Text -> println("Text: ${frame.readText()}")
186
is Frame.Binary -> println("Binary: ${frame.data.size} bytes")
187
is Frame.Ping -> send(Frame.Pong(frame.data))
188
is Frame.Pong -> println("Pong received")
189
is Frame.Close -> {
190
println("Close: ${frame.readReason()}")
191
break
192
}
193
}
194
}
195
}
196
```
197
198
### Connection Monitoring
199
200
Monitor connection state and handle disconnections:
201
202
```kotlin
203
client.webSocket("ws://example.com") {
204
// Launch a coroutine to monitor connection
205
launch {
206
try {
207
// Wait for close reason
208
val reason = closeReason.await()
209
println("Connection closed: $reason")
210
} catch (e: Exception) {
211
println("Connection error: ${e.message}")
212
}
213
}
214
215
// Main message processing
216
try {
217
for (frame in incoming) {
218
// Process frames...
219
}
220
} catch (e: ClosedReceiveChannelException) {
221
println("Connection was closed")
222
}
223
}
224
```
225
226
## Advanced Session Features
227
228
### Extension Access
229
230
Access WebSocket extensions through the session:
231
232
```kotlin
233
client.webSocket("ws://example.com") {
234
// Access WebSocket extensions (if supported by engine)
235
val extensions = call.attributes.getOrNull(extensionsKey)
236
extensions?.forEach { extension ->
237
println("Active extension: ${extension.factory.key}")
238
}
239
}
240
```
241
242
### Custom Session Handling
243
244
Implement custom session behavior by working with the underlying session:
245
246
```kotlin
247
internal class CustomClientWebSocketSession(
248
override val call: HttpClientCall,
249
private val delegate: WebSocketSession
250
) : ClientWebSocketSession, WebSocketSession by delegate {
251
252
suspend fun sendWithTimestamp(message: String) {
253
val timestamped = "${System.currentTimeMillis()}: $message"
254
send(timestamped)
255
}
256
}
257
```
258
259
### Session Debugging
260
261
Debug WebSocket sessions using call context:
262
263
```kotlin
264
client.webSocket("ws://example.com") {
265
println("=== WebSocket Session Debug Info ===")
266
println("URL: ${call.request.url}")
267
println("Method: ${call.request.method}")
268
println("Headers: ${call.request.headers.entries()}")
269
println("Response Status: ${call.response.status}")
270
println("Response Headers: ${call.response.headers.entries()}")
271
println("===================================")
272
273
// Continue with normal WebSocket operations...
274
}
275
```
276
277
## Error Handling
278
279
Session-related errors and their handling:
280
281
```kotlin
282
try {
283
val session = client.webSocketSession("ws://invalid.com")
284
// Use session...
285
} catch (e: WebSocketException) {
286
println("WebSocket handshake failed: ${e.message}")
287
} catch (e: ConnectTimeoutException) {
288
println("Connection timeout")
289
} catch (e: Exception) {
290
println("Other connection error: ${e.message}")
291
}
292
```
293
294
Session cleanup on errors:
295
296
```kotlin
297
var session: DefaultClientWebSocketSession? = null
298
try {
299
session = client.webSocketSession("ws://example.com")
300
// Use session...
301
} catch (e: Exception) {
302
println("Error occurred: ${e.message}")
303
} finally {
304
session?.close()
305
}
306
```