or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

address-types.mddatagram-sockets.mdindex.mdselectors.mdsocket-builders.mdsocket-interfaces.mdsocket-options.mdutilities.md

socket-options.mddocs/

0

# Socket Options

1

2

Ktor Network provides a comprehensive socket configuration system through typed options classes. The options system allows fine-tuning of socket behavior, performance characteristics, and network properties.

3

4

## Base Options Classes

5

6

### Socket Options Hierarchy

7

8

```kotlin { .api }

9

sealed class SocketOptions

10

11

class SocketOptions.PeerSocketOptions : SocketOptions() {

12

var sendBufferSize: Int? = null

13

var receiveBufferSize: Int? = null

14

var reuseAddress: Boolean = true

15

var reusePort: Boolean = false

16

}

17

```

18

19

Base options class providing buffer size and address reuse settings for peer connections.

20

21

**Properties:**

22

- `sendBufferSize: Int?` - Send buffer size in bytes (null = system default)

23

- `receiveBufferSize: Int?` - Receive buffer size in bytes (null = system default)

24

- `reuseAddress: Boolean` - Allow address reuse (default: false)

25

- `reusePort: Boolean` - Allow port reuse (default: false)

26

27

## TCP Socket Options

28

29

### TCP Client Options

30

31

```kotlin { .api }

32

class SocketOptions.TCPClientSocketOptions : SocketOptions.PeerSocketOptions() {

33

var keepAlive: Boolean? = null

34

var noDelay: Boolean = true

35

var lingerSeconds: Int = -1

36

var socketTimeout: Long = INFINITE_TIMEOUT_MS

37

}

38

```

39

40

TCP-specific options for client connections and general TCP behavior.

41

42

**Properties:**

43

- `keepAlive: Boolean?` - Enable TCP keepalive probes (null = system default)

44

- `noDelay: Boolean` - Disable Nagle's algorithm for lower latency (default: true)

45

- `lingerSeconds: Int` - Linger time in seconds on close (-1 = system default, not set)

46

- `socketTimeout: Long` - Socket timeout in milliseconds (default: INFINITE_TIMEOUT_MS)

47

48

## UDP Socket Options

49

50

### UDP Options

51

52

```kotlin { .api }

53

class SocketOptions.UDPSocketOptions : SocketOptions.PeerSocketOptions() {

54

var broadcast: Boolean? = null

55

}

56

```

57

58

UDP-specific options for datagram communication.

59

60

**Properties:**

61

- `broadcast: Boolean?` - Enable broadcast packet transmission (null = system default)

62

63

## Server Socket Options

64

65

### Acceptor Options

66

67

```kotlin { .api }

68

class SocketOptions.AcceptorOptions : SocketOptions() {

69

var backlogSize: Int = 511

70

var reuseAddress: Boolean = true

71

var reusePort: Boolean = false

72

}

73

```

74

75

Options specific to server sockets that accept connections.

76

77

**Properties:**

78

- `backlogSize: Int` - Maximum pending connection queue size (default: 511)

79

- `reuseAddress: Boolean` - Allow address reuse (default: true)

80

- `reusePort: Boolean` - Allow multiple sockets to bind to same port (default: false)

81

82

## Configuration Interface

83

84

### Configurable Interface

85

86

```kotlin { .api }

87

interface Configurable<out T : Configurable<T, Options>, Options : SocketOptions> {

88

fun configure(block: Options.() -> Unit): T

89

}

90

```

91

92

Interface enabling fluent configuration of socket builders with type-safe options.

93

94

## Usage Examples

95

96

### TCP Client Configuration

97

98

```kotlin

99

import io.ktor.network.sockets.*

100

import io.ktor.network.selector.*

101

102

suspend fun createOptimizedTcpClient() {

103

val selectorManager = SelectorManager()

104

105

val socket = aSocket(selectorManager)

106

.tcp()

107

.configure {

108

// Performance optimizations

109

noDelay = true // Disable Nagle's algorithm

110

keepAlive = true // Enable keepalive

111

socketTimeout = 30000 // 30 second timeout

112

113

// Buffer sizing

114

sendBufferSize = 64 * 1024 // 64KB send buffer

115

receiveBufferSize = 64 * 1024 // 64KB receive buffer

116

117

// Address reuse

118

reuseAddress = true

119

reusePort = false

120

121

// Connection cleanup

122

lingerSeconds = 0 // Close immediately

123

}

124

.connect(InetSocketAddress("api.example.com", 443))

125

126

println("Optimized TCP connection established")

127

socket.close()

128

selectorManager.close()

129

}

130

```

131

132

### TCP Server Configuration

133

134

```kotlin

135

suspend fun createHighPerformanceServer() {

136

val selectorManager = SelectorManager()

137

138

val serverSocket = aSocket(selectorManager)

139

.tcp()

140

.configure {

141

// Server-specific options

142

backlogSize = 1000 // Large connection queue

143

reuseAddress = true // Allow quick restart

144

reusePort = true // Allow load balancing

145

146

// Buffer optimization

147

sendBufferSize = 128 * 1024 // 128KB send buffer

148

receiveBufferSize = 128 * 1024 // 128KB receive buffer

149

}

150

.bind(InetSocketAddress("0.0.0.0", 8080))

151

152

println("High-performance server listening on ${serverSocket.localAddress}")

153

154

// Accept connections with client-specific options

155

while (!serverSocket.isClosed) {

156

val clientSocket = serverSocket.accept()

157

158

// Client connection inherits server buffer settings

159

println("Client connected: ${clientSocket.remoteAddress}")

160

161

// Handle client in coroutine

162

launch {

163

handleClient(clientSocket)

164

}

165

}

166

167

serverSocket.close()

168

selectorManager.close()

169

}

170

171

suspend fun handleClient(client: Socket) {

172

// Client handling logic

173

client.close()

174

}

175

```

176

177

### UDP Socket Configuration

178

179

```kotlin

180

suspend fun createBroadcastUdpSocket() {

181

val selectorManager = SelectorManager()

182

183

val socket = aSocket(selectorManager)

184

.udp()

185

.configure {

186

// Enable broadcast transmission

187

broadcast = true

188

189

// Larger buffers for bulk data

190

sendBufferSize = 256 * 1024 // 256KB for large datagrams

191

receiveBufferSize = 256 * 1024

192

193

// Address reuse for multi-instance deployment

194

reuseAddress = true

195

reusePort = true

196

}

197

.bind(InetSocketAddress("0.0.0.0", 9999))

198

199

// Can now send broadcast packets

200

val broadcastDatagram = Datagram(

201

packet = ByteReadPacket("Broadcast message".toByteArray()),

202

address = InetSocketAddress("255.255.255.255", 9999)

203

)

204

205

socket.send(broadcastDatagram)

206

println("Broadcast sent")

207

208

socket.close()

209

selectorManager.close()

210

}

211

```

212

213

### Performance Tuning Examples

214

215

```kotlin

216

suspend fun createLowLatencyConnection() {

217

val selectorManager = SelectorManager()

218

219

// Low-latency configuration

220

val socket = aSocket(selectorManager)

221

.tcp()

222

.configure {

223

noDelay = true // Immediate transmission

224

keepAlive = false // Reduce overhead

225

lingerSeconds = 0 // Fast close

226

socketTimeout = 5000 // Quick timeout

227

228

// Smaller buffers for lower latency

229

sendBufferSize = 8 * 1024 // 8KB

230

receiveBufferSize = 8 * 1024 // 8KB

231

}

232

.connect(InetSocketAddress("low-latency-service.com", 7777))

233

234

println("Low-latency connection established")

235

socket.close()

236

selectorManager.close()

237

}

238

239

suspend fun createHighThroughputConnection() {

240

val selectorManager = SelectorManager()

241

242

// High-throughput configuration

243

val socket = aSocket(selectorManager)

244

.tcp()

245

.configure {

246

noDelay = false // Allow batching (Nagle's algorithm)

247

keepAlive = true // Keep connections alive

248

socketTimeout = 300000 // Long timeout (5 minutes)

249

250

// Large buffers for bulk transfer

251

sendBufferSize = 1024 * 1024 // 1MB

252

receiveBufferSize = 1024 * 1024 // 1MB

253

254

lingerSeconds = 30 // Graceful close

255

}

256

.connect(InetSocketAddress("bulk-transfer.com", 8888))

257

258

println("High-throughput connection established")

259

socket.close()

260

selectorManager.close()

261

}

262

```

263

264

### Platform-Specific Configuration

265

266

```kotlin

267

suspend fun createMacOSOptimizedSocket() {

268

val selectorManager = SelectorManager()

269

270

val socket = aSocket(selectorManager)

271

.tcp()

272

.configure {

273

// macOS-specific optimizations

274

keepAlive = true

275

noDelay = true

276

277

// Optimal buffer sizes for macOS ARM64

278

sendBufferSize = 256 * 1024 // 256KB

279

receiveBufferSize = 256 * 1024

280

281

// Port reuse for development

282

reuseAddress = true

283

reusePort = true

284

285

// Reasonable timeout

286

socketTimeout = 60000 // 1 minute

287

}

288

.connect(InetSocketAddress("localhost", 8080))

289

290

println("macOS optimized connection")

291

socket.close()

292

selectorManager.close()

293

}

294

```

295

296

### Configuration Patterns

297

298

```kotlin

299

// Define reusable configuration functions

300

fun SocketOptions.TCPClientSocketOptions.applyWebClientDefaults() {

301

keepAlive = true

302

noDelay = true

303

socketTimeout = 30000

304

sendBufferSize = 32 * 1024

305

receiveBufferSize = 32 * 1024

306

reuseAddress = true

307

}

308

309

fun SocketOptions.TCPClientSocketOptions.applyGameClientDefaults() {

310

keepAlive = true

311

noDelay = true // Low latency priority

312

socketTimeout = 5000 // Quick timeout

313

sendBufferSize = 16 * 1024 // Smaller buffers

314

receiveBufferSize = 16 * 1024

315

lingerSeconds = 0 // Fast close

316

}

317

318

fun SocketOptions.AcceptorOptions.applyWebServerDefaults() {

319

backlogSize = 1000

320

reuseAddress = true

321

reusePort = false

322

}

323

324

suspend fun useConfigurationPatterns() {

325

val selectorManager = SelectorManager()

326

327

// Web client with defaults

328

val webClient = aSocket(selectorManager)

329

.tcp()

330

.configure { applyWebClientDefaults() }

331

.connect(InetSocketAddress("api.example.com", 80))

332

333

// Game client with low-latency defaults

334

val gameClient = aSocket(selectorManager)

335

.tcp()

336

.configure { applyGameClientDefaults() }

337

.connect(InetSocketAddress("game-server.com", 7777))

338

339

// Web server with defaults

340

val webServer = aSocket(selectorManager)

341

.tcp()

342

.configure { applyWebServerDefaults() }

343

.bind(InetSocketAddress("0.0.0.0", 8080))

344

345

// Clean up

346

webClient.close()

347

gameClient.close()

348

webServer.close()

349

selectorManager.close()

350

}

351

```

352

353

## Option Value Guidelines

354

355

### Buffer Sizes

356

- **Small buffers (4-16KB)**: Low-latency applications, real-time communication

357

- **Medium buffers (32-64KB)**: General purpose applications, web services

358

- **Large buffers (128KB-1MB)**: Bulk data transfer, file streaming

359

360

### Timeouts

361

- **Short timeouts (1-5 seconds)**: Interactive applications, real-time services

362

- **Medium timeouts (30-60 seconds)**: Web applications, API clients

363

- **Long timeouts (5+ minutes)**: Bulk operations, file transfers

364

365

### TCP Options

366

- **noDelay = true**: Low-latency priority (gaming, real-time)

367

- **noDelay = false**: Throughput priority (bulk transfer)

368

- **keepAlive = true**: Long-lived connections

369

- **keepAlive = false**: Short-lived connections

370

371

## Type Definitions

372

373

### Required Import Statements

374

375

```kotlin

376

import io.ktor.network.sockets.*

377

```

378

379

### Related Types

380

381

- Configuration is used with builders - See [Socket Builders](./socket-builders.md)

382

- Options affect all socket types - See [Socket Interfaces](./socket-interfaces.md)

383

- UDP options are specific - See [Datagram Sockets](./datagram-sockets.md)