or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

frame-operations.mdindex.mdplugin-configuration.mdserialization-support.mdsession-management.mdwebsocket-connections.md

websocket-connections.mddocs/

0

# WebSocket Connections

1

2

Core connection establishment functions for creating WebSocket sessions with flexible configuration options, supporting both secure and insecure connections with automatic protocol handling.

3

4

## Capabilities

5

6

### WebSocket Connection Function

7

8

Opens a WebSocket connection and executes a block with the session, automatically handling connection lifecycle.

9

10

```kotlin { .api }

11

/**

12

* Opens a WebSocket connection and executes block with DefaultClientWebSocketSession

13

* Connection is automatically closed after block execution

14

* @param request Configuration block for HTTP request

15

* @param block Suspend block executed with WebSocket session

16

*/

17

suspend fun HttpClient.webSocket(

18

request: HttpRequestBuilder.() -> Unit,

19

block: suspend DefaultClientWebSocketSession.() -> Unit

20

)

21

22

/**

23

* Opens a WebSocket connection with host/port/path parameters

24

* @param method HTTP method (default: GET)

25

* @param host WebSocket server host

26

* @param port WebSocket server port

27

* @param path WebSocket endpoint path

28

* @param request Additional request configuration

29

* @param block Suspend block executed with WebSocket session

30

*/

31

suspend fun HttpClient.webSocket(

32

method: HttpMethod = HttpMethod.Get,

33

host: String? = null,

34

port: Int? = null,

35

path: String? = null,

36

request: HttpRequestBuilder.() -> Unit = {},

37

block: suspend DefaultClientWebSocketSession.() -> Unit

38

)

39

40

/**

41

* Opens a WebSocket connection using URL string

42

* @param urlString WebSocket URL (ws:// or wss://)

43

* @param request Additional request configuration

44

* @param block Suspend block executed with WebSocket session

45

*/

46

suspend fun HttpClient.webSocket(

47

urlString: String,

48

request: HttpRequestBuilder.() -> Unit = {},

49

block: suspend DefaultClientWebSocketSession.() -> Unit

50

)

51

```

52

53

**Usage Examples:**

54

55

```kotlin

56

// Basic WebSocket connection

57

client.webSocket("ws://echo.websocket.org") {

58

send("Hello WebSocket!")

59

60

for (frame in incoming) {

61

when (frame) {

62

is Frame.Text -> println("Received: ${frame.readText()}")

63

}

64

}

65

}

66

67

// WebSocket with custom headers

68

client.webSocket(

69

method = HttpMethod.Get,

70

host = "localhost",

71

port = 8080,

72

path = "/websocket",

73

request = {

74

header("Authorization", "Bearer $token")

75

parameter("room", "general")

76

}

77

) {

78

// WebSocket session logic

79

}

80

81

// WebSocket with URL and parameters

82

client.webSocket("ws://chat.example.com/room/123") {

83

// Session handling

84

}

85

```

86

87

### WebSocket Session Creation

88

89

Creates and returns a WebSocket session without automatic closure, allowing manual session management.

90

91

```kotlin { .api }

92

/**

93

* Opens a WebSocket session and returns it for manual management

94

* Session must be manually closed when done

95

* @param block Configuration block for HTTP request

96

* @return DefaultClientWebSocketSession for manual management

97

*/

98

suspend fun HttpClient.webSocketSession(

99

block: HttpRequestBuilder.() -> Unit

100

): DefaultClientWebSocketSession

101

102

/**

103

* Opens a WebSocket session with host/port/path parameters

104

* @param method HTTP method (default: GET)

105

* @param host WebSocket server host

106

* @param port WebSocket server port

107

* @param path WebSocket endpoint path

108

* @param block Additional request configuration

109

* @return DefaultClientWebSocketSession for manual management

110

*/

111

suspend fun HttpClient.webSocketSession(

112

method: HttpMethod = HttpMethod.Get,

113

host: String? = null,

114

port: Int? = null,

115

path: String? = null,

116

block: HttpRequestBuilder.() -> Unit = {}

117

): DefaultClientWebSocketSession

118

119

/**

120

* Opens a WebSocket session using URL string

121

* @param urlString WebSocket URL (ws:// or wss://)

122

* @param block Additional request configuration

123

* @return DefaultClientWebSocketSession for manual management

124

*/

125

suspend fun HttpClient.webSocketSession(

126

urlString: String,

127

block: HttpRequestBuilder.() -> Unit = {}

128

): DefaultClientWebSocketSession

129

```

130

131

**Usage Examples:**

132

133

```kotlin

134

// Manual session management

135

val session = client.webSocketSession("ws://echo.websocket.org")

136

try {

137

session.send("Hello!")

138

val response = session.incoming.receive()

139

println("Received: ${(response as Frame.Text).readText()}")

140

} finally {

141

session.close()

142

}

143

144

// Session with custom configuration

145

val session = client.webSocketSession(

146

host = "api.example.com",

147

port = 443,

148

path = "/websocket/v1"

149

) {

150

header("User-Agent", "MyApp/1.0")

151

url.protocol = URLProtocol.WSS

152

}

153

```

154

155

### WebSocket Shorthand (ws)

156

157

Convenient shorthand functions for WebSocket connections, identical to webSocket functions.

158

159

```kotlin { .api }

160

/**

161

* Shorthand for webSocket function with host/port/path parameters

162

* @param method HTTP method (default: GET)

163

* @param host WebSocket server host

164

* @param port WebSocket server port

165

* @param path WebSocket endpoint path

166

* @param request Additional request configuration

167

* @param block Suspend block executed with WebSocket session

168

*/

169

suspend fun HttpClient.ws(

170

method: HttpMethod = HttpMethod.Get,

171

host: String? = null,

172

port: Int? = null,

173

path: String? = null,

174

request: HttpRequestBuilder.() -> Unit = {},

175

block: suspend DefaultClientWebSocketSession.() -> Unit

176

)

177

178

/**

179

* Shorthand for webSocket function with request configuration

180

* @param request Configuration block for HTTP request

181

* @param block Suspend block executed with WebSocket session

182

*/

183

suspend fun HttpClient.ws(

184

request: HttpRequestBuilder.() -> Unit,

185

block: suspend DefaultClientWebSocketSession.() -> Unit

186

)

187

188

/**

189

* Shorthand for webSocket function with URL string

190

* @param urlString WebSocket URL (ws:// or wss://)

191

* @param request Additional request configuration

192

* @param block Suspend block executed with WebSocket session

193

*/

194

suspend fun HttpClient.ws(

195

urlString: String,

196

request: HttpRequestBuilder.() -> Unit = {},

197

block: suspend DefaultClientWebSocketSession.() -> Unit

198

)

199

```

200

201

### Secure WebSocket (wss)

202

203

Secure WebSocket connection functions that automatically use WSS protocol.

204

205

```kotlin { .api }

206

/**

207

* Opens a secure WebSocket (WSS) connection with request configuration

208

* Automatically sets protocol to WSS and default port to 443

209

* @param request Configuration block for HTTPS request

210

* @param block Suspend block executed with WebSocket session

211

*/

212

suspend fun HttpClient.wss(

213

request: HttpRequestBuilder.() -> Unit,

214

block: suspend DefaultClientWebSocketSession.() -> Unit

215

)

216

217

/**

218

* Opens a secure WebSocket (WSS) connection using URL string

219

* @param urlString WebSocket URL (should use wss:// scheme)

220

* @param request Additional request configuration

221

* @param block Suspend block executed with WebSocket session

222

*/

223

suspend fun HttpClient.wss(

224

urlString: String,

225

request: HttpRequestBuilder.() -> Unit = {},

226

block: suspend DefaultClientWebSocketSession.() -> Unit

227

)

228

229

/**

230

* Opens a secure WebSocket (WSS) connection with host/port/path parameters

231

* Automatically sets protocol to WSS

232

* @param method HTTP method (default: GET)

233

* @param host WebSocket server host

234

* @param port WebSocket server port (default: 443 for WSS)

235

* @param path WebSocket endpoint path

236

* @param request Additional request configuration

237

* @param block Suspend block executed with WebSocket session

238

*/

239

suspend fun HttpClient.wss(

240

method: HttpMethod = HttpMethod.Get,

241

host: String? = null,

242

port: Int? = null,

243

path: String? = null,

244

request: HttpRequestBuilder.() -> Unit = {},

245

block: suspend DefaultClientWebSocketSession.() -> Unit

246

)

247

```

248

249

**Usage Examples:**

250

251

```kotlin

252

// Secure WebSocket with URL

253

client.wss("wss://secure-echo.websocket.org") {

254

send("Secure message")

255

for (frame in incoming) {

256

when (frame) {

257

is Frame.Text -> println("Secure response: ${frame.readText()}")

258

}

259

}

260

}

261

262

// Secure WebSocket with host/port

263

client.wss(

264

host = "api.example.com",

265

path = "/secure-websocket"

266

) {

267

// Session runs over TLS

268

}

269

270

// Secure WebSocket with authentication

271

client.wss(

272

request = {

273

url("wss://secure-api.example.com/websocket")

274

header("Authorization", "Bearer $accessToken")

275

}

276

) {

277

// Authenticated secure session

278

}

279

```

280

281

## Connection Examples

282

283

### Basic Echo Server

284

285

```kotlin

286

client.webSocket("ws://echo.websocket.org") {

287

// Send message

288

send("Hello from Ktor!")

289

290

// Receive echo

291

val frame = incoming.receive()

292

if (frame is Frame.Text) {

293

println("Echo: ${frame.readText()}")

294

}

295

}

296

```

297

298

### Chat Application

299

300

```kotlin

301

client.webSocket(

302

host = "chat.example.com",

303

path = "/chat"

304

) {

305

// Join chat room

306

send("JOIN:general")

307

308

// Send and receive messages

309

launch {

310

while (true) {

311

val message = readLine() ?: break

312

send("MESSAGE:$message")

313

}

314

}

315

316

for (frame in incoming) {

317

when (frame) {

318

is Frame.Text -> {

319

val message = frame.readText()

320

println("Chat: $message")

321

}

322

is Frame.Close -> break

323

}

324

}

325

}

326

```

327

328

### Secure Trading WebSocket

329

330

```kotlin

331

client.wss(

332

host = "api.exchange.com",

333

path = "/ws/v1/stream"

334

) {

335

// Subscribe to price feeds

336

send("""{"action":"subscribe","symbols":["BTCUSD","ETHUSD"]}""")

337

338

for (frame in incoming) {

339

when (frame) {

340

is Frame.Text -> {

341

val data = json.decodeFromString<PriceUpdate>(frame.readText())

342

handlePriceUpdate(data)

343

}

344

}

345

}

346

}

347

```

348

349

### Custom Headers and Parameters

350

351

```kotlin

352

client.webSocket(

353

urlString = "wss://api.example.com/websocket",

354

request = {

355

header("User-Agent", "MyApp/1.0.0")

356

header("Authorization", "ApiKey $apiKey")

357

parameter("version", "v2")

358

parameter("format", "json")

359

}

360

) {

361

// WebSocket session with custom headers

362

}

363

```