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

index.mddocs/

0

# Ktor Client WebSockets

1

2

Ktor Client WebSockets provides comprehensive WebSocket client capabilities for Kotlin applications running on Linux x64 platforms. As part of the Ktor framework, it enables full-duplex, real-time communication between clients and servers over a single TCP connection with native performance optimizations.

3

4

## Package Information

5

6

- **Package Name**: ktor-client-websockets-linuxx64

7

- **Package Type**: Maven

8

- **Language**: Kotlin

9

- **Platform**: Linux x64 (Native)

10

- **Installation**: Add to your `build.gradle.kts`:

11

12

```kotlin

13

dependencies {

14

implementation("io.ktor:ktor-client-websockets-linuxx64:3.2.0")

15

}

16

```

17

18

## Core Imports

19

20

```kotlin

21

import io.ktor.client.*

22

import io.ktor.client.plugins.websocket.*

23

import io.ktor.websocket.*

24

```

25

26

For WebSocket frames:

27

28

```kotlin

29

import io.ktor.websocket.Frame

30

import io.ktor.websocket.FrameType

31

```

32

33

## Basic Usage

34

35

```kotlin

36

import io.ktor.client.*

37

import io.ktor.client.plugins.websocket.*

38

import io.ktor.websocket.*

39

import kotlin.time.Duration.Companion.seconds

40

41

// Install WebSocket plugin

42

val client = HttpClient {

43

install(WebSockets) {

44

pingInterval = 30.seconds

45

maxFrameSize = 1024 * 1024 // 1MB

46

}

47

}

48

49

// Connect and use WebSocket

50

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

51

// Send text message

52

send("Hello WebSocket!")

53

54

// Receive messages

55

for (frame in incoming) {

56

when (frame) {

57

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

58

is Frame.Binary -> println("Received binary: ${frame.data.size} bytes")

59

is Frame.Close -> break

60

}

61

}

62

}

63

64

client.close()

65

```

66

67

## Architecture

68

69

Ktor WebSocket client is built around several key components:

70

71

- **Plugin System**: WebSocket functionality is provided as a client plugin that integrates with Ktor's HTTP client

72

- **Session Management**: WebSocket connections are managed through session interfaces with lifecycle control

73

- **Frame Processing**: Low-level WebSocket frame handling with support for text, binary, and control frames

74

- **Extension Support**: Pluggable WebSocket extensions system for protocol enhancements

75

- **Serialization**: Content converter integration for automatic serialization/deserialization

76

- **Coroutine Integration**: Full async/await support using Kotlin coroutines

77

78

## Capabilities

79

80

### Plugin Configuration

81

82

WebSocket plugin installation and configuration with ping intervals, frame size limits, and extension support.

83

84

```kotlin { .api }

85

class WebSockets internal constructor(

86

val pingIntervalMillis: Long,

87

val maxFrameSize: Long,

88

val contentConverter: WebsocketContentConverter? = null

89

) : HttpClientPlugin<WebSockets.Config, WebSockets>

90

91

class Config {

92

var pingIntervalMillis: Long

93

var maxFrameSize: Long

94

var contentConverter: WebsocketContentConverter?

95

var pingInterval: Duration?

96

fun extensions(block: WebSocketExtensionsConfig.() -> Unit)

97

}

98

99

fun HttpClientConfig<*>.WebSockets(config: WebSockets.Config.() -> Unit)

100

```

101

102

[Plugin Configuration](./plugin-configuration.md)

103

104

### WebSocket Connections

105

106

Core connection establishment functions for creating WebSocket sessions with various configuration options.

107

108

```kotlin { .api }

109

suspend fun HttpClient.webSocket(

110

request: HttpRequestBuilder.() -> Unit,

111

block: suspend DefaultClientWebSocketSession.() -> Unit

112

)

113

114

suspend fun HttpClient.webSocketSession(

115

block: HttpRequestBuilder.() -> Unit

116

): DefaultClientWebSocketSession

117

118

suspend fun HttpClient.ws(

119

host: String? = null,

120

port: Int? = null,

121

path: String? = null,

122

block: suspend DefaultClientWebSocketSession.() -> Unit

123

)

124

125

suspend fun HttpClient.wss(

126

host: String? = null,

127

port: Int? = null,

128

path: String? = null,

129

block: suspend DefaultClientWebSocketSession.() -> Unit

130

)

131

```

132

133

[WebSocket Connections](./websocket-connections.md)

134

135

### Session Management

136

137

WebSocket session interfaces providing frame-level control and connection lifecycle management.

138

139

```kotlin { .api }

140

interface ClientWebSocketSession : WebSocketSession {

141

val call: HttpClientCall

142

}

143

144

class DefaultClientWebSocketSession(

145

override val call: HttpClientCall,

146

delegate: DefaultWebSocketSession

147

) : ClientWebSocketSession, DefaultWebSocketSession

148

149

interface WebSocketSession : CoroutineScope {

150

var masking: Boolean

151

var maxFrameSize: Long

152

val incoming: ReceiveChannel<Frame>

153

val outgoing: SendChannel<Frame>

154

val extensions: List<WebSocketExtension<*>>

155

}

156

```

157

158

[Session Management](./session-management.md)

159

160

### Frame Operations

161

162

Low-level WebSocket frame handling for text, binary, and control frame processing.

163

164

```kotlin { .api }

165

sealed class Frame {

166

val fin: Boolean

167

val frameType: FrameType

168

val data: ByteArray

169

val rsv1: Boolean

170

val rsv2: Boolean

171

val rsv3: Boolean

172

173

class Text(text: String) : Frame

174

class Binary(fin: Boolean, data: ByteArray) : Frame

175

class Close : Frame

176

class Ping(data: ByteArray) : Frame

177

class Pong(data: ByteArray) : Frame

178

}

179

180

enum class FrameType(val controlFrame: Boolean, val opcode: Int) {

181

TEXT, BINARY, CLOSE, PING, PONG

182

}

183

184

fun Frame.Text.readText(): String

185

fun Frame.readBytes(): ByteArray

186

fun Frame.Close.readReason(): CloseReason?

187

```

188

189

[Frame Operations](./frame-operations.md)

190

191

### Serialization Support

192

193

Content converter integration for automatic serialization/deserialization of objects to/from WebSocket frames.

194

195

```kotlin { .api }

196

suspend fun DefaultClientWebSocketSession.sendSerialized(data: Any?, typeInfo: TypeInfo)

197

suspend inline fun <reified T> DefaultClientWebSocketSession.sendSerialized(data: T)

198

199

suspend fun <T> DefaultClientWebSocketSession.receiveDeserialized(typeInfo: TypeInfo): T

200

suspend inline fun <reified T> DefaultClientWebSocketSession.receiveDeserialized(): T

201

202

val DefaultClientWebSocketSession.converter: WebsocketContentConverter?

203

```

204

205

[Serialization Support](./serialization-support.md)

206

207

## Types

208

209

### WebSocket Configuration Types

210

211

```kotlin { .api }

212

interface WebsocketContentConverter {

213

suspend fun serialize(

214

charset: Charset,

215

typeInfo: TypeInfo,

216

value: Any?

217

): Frame

218

219

suspend fun deserialize(

220

charset: Charset,

221

typeInfo: TypeInfo,

222

content: Frame

223

): Any?

224

}

225

226

data object WebSocketCapability : HttpClientEngineCapability<Unit>

227

data object WebSocketExtensionsCapability : HttpClientEngineCapability<Unit>

228

```

229

230

### WebSocket Constants

231

232

```kotlin { .api }

233

/** Constant indicating that WebSocket pinger is disabled */

234

const val PINGER_DISABLED: Long = 0

235

```

236

237

### Exception Types

238

239

```kotlin { .api }

240

class WebSocketException(message: String, cause: Throwable?) : IllegalStateException

241

242

class ProtocolViolationException(message: String) : Exception

243

244

class FrameTooBigException(message: String) : Exception

245

```

246

247

### Extension Types

248

249

```kotlin { .api }

250

interface WebSocketExtension<ConfigType : Any> {

251

val protocols: List<WebSocketExtensionHeader>

252

fun clientNegotiation(extensions: List<WebSocketExtensionHeader>): Boolean

253

}

254

255

interface WebSocketExtensionFactory<ConfigType : Any, ExtensionType : WebSocketExtension<ConfigType>>

256

257

class WebSocketExtensionsConfig {

258

fun <Config : Any, Extension : WebSocketExtension<Config>> install(

259

extension: WebSocketExtensionFactory<Config, Extension>,

260

configure: Config.() -> Unit = {}

261

)

262

}

263

264

class WebSocketExtensionHeader(val name: String, val parameters: List<String>)

265

266

/** Parse WebSocket extension headers from HTTP header value */

267

fun parseWebSocketExtensions(value: String): List<WebSocketExtensionHeader>

268

```

269

270

## Error Handling

271

272

WebSocket operations can throw several types of exceptions:

273

274

- **WebSocketException**: General WebSocket protocol errors, handshake failures, or connection issues

275

- **ProtocolViolationException**: WebSocket protocol compliance violations

276

- **FrameTooBigException**: Frame size exceeds configured maximum

277

- **ClosedReceiveChannelException**: Channel closed while receiving

278

- **WebsocketConverterNotFoundException**: No content converter available for serialization

279

- **WebsocketDeserializeException**: Deserialization failed for received frame