0
# WebSocket Connections
1
2
Connection establishment functions providing flexible ways to connect to WebSocket servers with both high-level and low-level APIs.
3
4
## Capabilities
5
6
### WebSocket Connection Functions
7
8
High-level functions that execute a block with an active WebSocket session and automatically handle connection cleanup.
9
10
```kotlin { .api }
11
/**
12
* Opens a WebSocket connection and executes a block with the session
13
* @param request Configuration block for the HTTP request
14
* @param block Suspend block executed with the WebSocket session
15
*/
16
suspend fun HttpClient.webSocket(
17
request: HttpRequestBuilder.() -> Unit,
18
block: suspend DefaultClientWebSocketSession.() -> Unit
19
)
20
21
/**
22
* Opens a WebSocket connection using method, host, port, and path parameters
23
* @param method HTTP method for the WebSocket handshake (default: GET)
24
* @param host Target hostname
25
* @param port Target port number
26
* @param path Target path
27
* @param request Additional request configuration
28
* @param block Suspend block executed with the WebSocket session
29
*/
30
suspend fun HttpClient.webSocket(
31
method: HttpMethod = HttpMethod.Get,
32
host: String? = null,
33
port: Int? = null,
34
path: String? = null,
35
request: HttpRequestBuilder.() -> Unit = {},
36
block: suspend DefaultClientWebSocketSession.() -> Unit
37
)
38
39
/**
40
* Opens a WebSocket connection using a URL string
41
* @param urlString WebSocket URL (ws:// or wss://)
42
* @param request Additional request configuration
43
* @param block Suspend block executed with the WebSocket session
44
*/
45
suspend fun HttpClient.webSocket(
46
urlString: String,
47
request: HttpRequestBuilder.() -> Unit = {},
48
block: suspend DefaultClientWebSocketSession.() -> Unit
49
)
50
```
51
52
**Usage Examples:**
53
54
```kotlin
55
// Connect using request builder
56
client.webSocket({
57
url("ws://echo.websocket.org")
58
header("Authorization", "Bearer token")
59
}) {
60
send("Hello!")
61
val response = incoming.receive()
62
// Handle response...
63
}
64
65
// Connect using parameters
66
client.webSocket(
67
method = HttpMethod.Get,
68
host = "echo.websocket.org",
69
port = 80,
70
path = "/websocket"
71
) {
72
send("Hello!")
73
// Handle messages...
74
}
75
76
// Connect using URL string
77
client.webSocket("ws://echo.websocket.org") {
78
send("Hello!")
79
// Handle messages...
80
}
81
```
82
83
### WebSocket Alias Functions
84
85
Shorter alias functions for WebSocket connections.
86
87
```kotlin { .api }
88
/**
89
* Alias for webSocket function using method, host, port, and path
90
*/
91
suspend fun HttpClient.ws(
92
method: HttpMethod = HttpMethod.Get,
93
host: String? = null,
94
port: Int? = null,
95
path: String? = null,
96
request: HttpRequestBuilder.() -> Unit = {},
97
block: suspend DefaultClientWebSocketSession.() -> Unit
98
)
99
100
/**
101
* Alias for webSocket function using request builder
102
*/
103
suspend fun HttpClient.ws(
104
request: HttpRequestBuilder.() -> Unit,
105
block: suspend DefaultClientWebSocketSession.() -> Unit
106
)
107
108
/**
109
* Alias for webSocket function using URL string
110
*/
111
suspend fun HttpClient.ws(
112
urlString: String,
113
request: HttpRequestBuilder.() -> Unit = {},
114
block: suspend DefaultClientWebSocketSession.() -> Unit
115
)
116
```
117
118
### Secure WebSocket Functions
119
120
Functions for establishing secure WebSocket connections (WSS).
121
122
```kotlin { .api }
123
/**
124
* Opens a secure WebSocket connection using request builder
125
* @param request Configuration block for the HTTPS request
126
* @param block Suspend block executed with the WebSocket session
127
*/
128
suspend fun HttpClient.wss(
129
request: HttpRequestBuilder.() -> Unit,
130
block: suspend DefaultClientWebSocketSession.() -> Unit
131
)
132
133
/**
134
* Opens a secure WebSocket connection using URL string
135
* @param urlString Secure WebSocket URL (wss://)
136
* @param request Additional request configuration
137
* @param block Suspend block executed with the WebSocket session
138
*/
139
suspend fun HttpClient.wss(
140
urlString: String,
141
request: HttpRequestBuilder.() -> Unit = {},
142
block: suspend DefaultClientWebSocketSession.() -> Unit
143
)
144
145
/**
146
* Opens a secure WebSocket connection using method, host, port, and path
147
* @param method HTTP method for the WebSocket handshake (default: GET)
148
* @param host Target hostname
149
* @param port Target port number (defaults to 443 for WSS)
150
* @param path Target path
151
* @param request Additional request configuration
152
* @param block Suspend block executed with the WebSocket session
153
*/
154
suspend fun HttpClient.wss(
155
method: HttpMethod = HttpMethod.Get,
156
host: String? = null,
157
port: Int? = null,
158
path: String? = null,
159
request: HttpRequestBuilder.() -> Unit = {},
160
block: suspend DefaultClientWebSocketSession.() -> Unit
161
)
162
```
163
164
**Usage Examples:**
165
166
```kotlin
167
// Secure connection using URL
168
client.wss("wss://secure.websocket.org") {
169
send("Secure message")
170
// Handle secure communication...
171
}
172
173
// Secure connection with custom headers
174
client.wss("wss://api.example.com/ws") {
175
header("Authorization", "Bearer ${getToken()}")
176
header("User-Agent", "MyApp/1.0")
177
} {
178
// WebSocket session handling...
179
}
180
181
// Secure connection using parameters
182
client.wss(
183
host = "secure.websocket.org",
184
port = 443,
185
path = "/secure-ws"
186
) {
187
send("Hello secure server!")
188
// Handle responses...
189
}
190
```
191
192
## Connection Lifecycle
193
194
### Automatic Cleanup
195
196
All connection functions (`webSocket`, `ws`, `wss`) automatically handle connection cleanup:
197
198
```kotlin
199
client.webSocket("ws://example.com") {
200
// Connection is established here
201
send("Hello!")
202
203
// Process messages
204
for (frame in incoming) {
205
// Handle frame...
206
}
207
208
// Connection is automatically closed when block exits
209
// Even if an exception occurs
210
}
211
```
212
213
### Connection State
214
215
Within the connection block, you have access to the full WebSocket session:
216
217
```kotlin
218
client.webSocket("ws://example.com") {
219
// Session properties
220
println("Connection established with ${call.request.url}")
221
222
// Send messages
223
send("Text message")
224
send(byteArrayOf(1, 2, 3, 4))
225
226
// Receive messages
227
for (frame in incoming) {
228
when (frame) {
229
is Frame.Text -> println("Text: ${frame.readText()}")
230
is Frame.Binary -> println("Binary: ${frame.data.size} bytes")
231
is Frame.Close -> {
232
println("Connection closed: ${frame.readReason()}")
233
break
234
}
235
else -> {}
236
}
237
}
238
}
239
```
240
241
## Error Handling
242
243
Connection functions throw `WebSocketException` for handshake failures or connection issues:
244
245
```kotlin
246
try {
247
client.webSocket("ws://invalid-server.com") {
248
// This block won't execute if handshake fails
249
}
250
} catch (e: WebSocketException) {
251
println("WebSocket connection failed: ${e.message}")
252
} catch (e: Exception) {
253
println("Other error: ${e.message}")
254
}
255
```
256
257
## Protocol Handling
258
259
### URL Protocol Conversion
260
261
The connection functions automatically handle protocol conversion:
262
263
- `webSocket` and `ws` functions convert HTTP URLs to WebSocket URLs (http:// → ws://, https:// → wss://)
264
- `wss` functions enforce secure WebSocket protocol (wss://)
265
- Default ports are handled automatically (80 for ws://, 443 for wss://)
266
267
### Request Customization
268
269
All connection functions accept request customization blocks:
270
271
```kotlin
272
client.webSocket("ws://example.com") {
273
// Customize the WebSocket handshake request
274
header("Authorization", "Bearer token")
275
header("Sec-WebSocket-Protocol", "chat, superchat")
276
parameter("room", "general")
277
userAgent("MyWebSocketClient/1.0")
278
} {
279
// WebSocket session handling...
280
}
281
```