or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdconnection-management.mdcontext-resources.mdhandlers.mdindex.mdrequest-logging.mdrequest-response.mdsecurity-ssl.mdserver-core.mdsession-management.mdutility-handlers.md

connection-management.mddocs/

0

# Connection Management

1

2

Connection management in Jetty handles network connectivity, protocol negotiation, SSL/TLS support, and connection lifecycle management through connectors and connection factories.

3

4

## Connection Factories

5

6

Connection factories create and configure protocol-specific connections.

7

8

### ConnectionFactory Interface

9

10

```java { .api }

11

public interface ConnectionFactory {

12

// Protocol identification

13

String getProtocol();

14

List<String> getProtocols();

15

16

// Connection creation

17

Connection newConnection(Connector connector, EndPoint endPoint);

18

19

// Nested interfaces

20

interface Detecting extends ConnectionFactory {

21

Detection detect(ByteBuffer buffer);

22

}

23

24

interface Configuring extends ConnectionFactory {

25

EndPoint configure(EndPoint endPoint, Connector connector, ConnectionMetaData connectionMetaData);

26

}

27

}

28

```

29

30

### AbstractConnectionFactory

31

32

Base implementation for connection factories.

33

34

```java { .api }

35

public abstract class AbstractConnectionFactory implements ConnectionFactory {

36

// Constructors

37

protected AbstractConnectionFactory(String protocol);

38

protected AbstractConnectionFactory(String... protocols);

39

40

// Protocol management

41

public String getProtocol();

42

public List<String> getProtocols();

43

44

// Template methods

45

public abstract Connection newConnection(Connector connector, EndPoint endPoint);

46

47

// Utility methods

48

protected void configure(Connection connection, Connector connector, EndPoint endPoint);

49

}

50

```

51

52

## HTTP Connection Factories

53

54

### HttpConnectionFactory

55

56

Factory for HTTP/1.1 connections.

57

58

```java { .api }

59

public class HttpConnectionFactory extends AbstractConnectionFactory

60

implements HttpConfiguration.ConnectionFactory {

61

62

// Constructors

63

public HttpConnectionFactory();

64

public HttpConnectionFactory(HttpConfiguration config);

65

public HttpConnectionFactory(HttpConfiguration config, String protocol);

66

67

// Configuration

68

public HttpConfiguration getHttpConfiguration();

69

public void setHttpConfiguration(HttpConfiguration config);

70

71

// Connection creation

72

public Connection newConnection(Connector connector, EndPoint endPoint);

73

}

74

```

75

76

### Usage Example

77

78

```java

79

// Create HTTP configuration

80

HttpConfiguration httpConfig = new HttpConfiguration();

81

httpConfig.setSecureScheme("https");

82

httpConfig.setSecurePort(8443);

83

httpConfig.setOutputBufferSize(32768);

84

httpConfig.setRequestHeaderSize(8192);

85

httpConfig.setResponseHeaderSize(8192);

86

87

// Create HTTP connection factory

88

HttpConnectionFactory httpFactory = new HttpConnectionFactory(httpConfig);

89

90

// Create connector with HTTP factory

91

ServerConnector httpConnector = new ServerConnector(server, httpFactory);

92

httpConnector.setPort(8080);

93

server.addConnector(httpConnector);

94

```

95

96

## SSL/TLS Connection Factory

97

98

### SslConnectionFactory

99

100

Factory for SSL/TLS encrypted connections.

101

102

```java { .api }

103

public class SslConnectionFactory extends AbstractConnectionFactory

104

implements ConnectionFactory.Detecting, ConnectionFactory.Configuring {

105

106

// Constructors

107

public SslConnectionFactory();

108

public SslConnectionFactory(String nextProtocol);

109

public SslConnectionFactory(SslContextFactory.Server sslContextFactory, String nextProtocol);

110

111

// SSL configuration

112

public SslContextFactory.Server getSslContextFactory();

113

public void setSslContextFactory(SslContextFactory.Server sslContextFactory);

114

115

// Protocol negotiation

116

public String getNextProtocol();

117

public void setNextProtocol(String nextProtocol);

118

119

// ALPN support

120

public boolean isDirectBuffersForEncryption();

121

public void setDirectBuffersForEncryption(boolean useDirectBuffers);

122

123

// Connection creation

124

public Connection newConnection(Connector connector, EndPoint endPoint);

125

public EndPoint configure(EndPoint endPoint, Connector connector,

126

ConnectionMetaData connectionMetaData);

127

}

128

```

129

130

### SSL Configuration Example

131

132

```java

133

// Create SSL context factory

134

SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();

135

sslContextFactory.setKeyStorePath("keystore.jks");

136

sslContextFactory.setKeyStorePassword("password");

137

sslContextFactory.setKeyManagerPassword("password");

138

sslContextFactory.setTrustStorePath("truststore.jks");

139

sslContextFactory.setTrustStorePassword("password");

140

141

// Enable client certificate authentication (optional)

142

sslContextFactory.setWantClientAuth(true);

143

sslContextFactory.setNeedClientAuth(false);

144

145

// Configure cipher suites

146

sslContextFactory.setIncludeCipherSuites("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384");

147

sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA");

148

149

// Configure protocols

150

sslContextFactory.setIncludeProtocols("TLSv1.2", "TLSv1.3");

151

sslContextFactory.setExcludeProtocols("SSLv2", "SSLv3", "TLSv1", "TLSv1.1");

152

153

// Create HTTP configuration for HTTPS

154

HttpConfiguration httpsConfig = new HttpConfiguration();

155

httpsConfig.setSecureScheme("https");

156

httpsConfig.setSecurePort(8443);

157

httpsConfig.addCustomizer(new SecureRequestCustomizer());

158

159

// Create HTTPS connector

160

ServerConnector httpsConnector = new ServerConnector(server,

161

new SslConnectionFactory(sslContextFactory, "http/1.1"),

162

new HttpConnectionFactory(httpsConfig));

163

httpsConnector.setPort(8443);

164

server.addConnector(httpsConnector);

165

```

166

167

## Protocol Detection

168

169

### DetectorConnectionFactory

170

171

Factory that detects protocols based on connection data.

172

173

```java { .api }

174

public class DetectorConnectionFactory extends AbstractConnectionFactory

175

implements ConnectionFactory.Detecting {

176

177

// Constructor

178

public DetectorConnectionFactory(ConnectionFactory... factories);

179

180

// Detection configuration

181

public void addDetectingConnectionFactory(ConnectionFactory.Detecting factory);

182

public List<ConnectionFactory.Detecting> getDetectingConnectionFactories();

183

184

// Connection creation

185

public Connection newConnection(Connector connector, EndPoint endPoint);

186

public Detection detect(ByteBuffer buffer);

187

}

188

```

189

190

### Usage Example

191

192

```java

193

// Create factories for different protocols

194

HttpConnectionFactory httpFactory = new HttpConnectionFactory();

195

HTTP2ServerConnectionFactory http2Factory = new HTTP2ServerConnectionFactory(httpConfig);

196

197

// Create detector that can handle both HTTP/1.1 and HTTP/2

198

DetectorConnectionFactory detector = new DetectorConnectionFactory(

199

httpFactory, http2Factory);

200

201

// Create connector with detection

202

ServerConnector connector = new ServerConnector(server, detector);

203

connector.setPort(8080);

204

```

205

206

## Connection Limiting and Control

207

208

### ConnectionLimit

209

210

Controls the maximum number of concurrent connections.

211

212

```java { .api }

213

public class ConnectionLimit extends AbstractLifeCycle

214

implements Connection.Listener, SelectorManager.AcceptListener {

215

216

// Constructor

217

public ConnectionLimit(int maxConnections, Connector... connectors);

218

219

// Configuration

220

public int getMaxConnections();

221

public void setMaxConnections(int maxConnections);

222

public int getConnections();

223

224

// Connection tracking

225

public void onOpened(Connection connection);

226

public void onClosed(Connection connection);

227

228

// Accept control

229

public void onAccepting(SelectableChannel channel);

230

public void onAcceptFailed(SelectableChannel channel, Throwable cause);

231

}

232

```

233

234

### AcceptRateLimit

235

236

Limits the rate of accepting new connections.

237

238

```java { .api }

239

public class AcceptRateLimit extends AbstractLifeCycle

240

implements SelectorManager.AcceptListener, Runnable {

241

242

// Constructor

243

public AcceptRateLimit(int maxRate, long period, TimeUnit units, Connector... connectors);

244

245

// Configuration

246

public int getMaxRate();

247

public void setMaxRate(int maxRate);

248

public long getPeriod();

249

public void setPeriod(long period, TimeUnit units);

250

251

// Rate tracking

252

public void onAccepting(SelectableChannel channel);

253

}

254

```

255

256

### Usage Example

257

258

```java

259

Server server = new Server();

260

ServerConnector connector = new ServerConnector(server);

261

connector.setPort(8080);

262

server.addConnector(connector);

263

264

// Limit to 1000 concurrent connections

265

ConnectionLimit connectionLimit = new ConnectionLimit(1000, connector);

266

server.addBean(connectionLimit);

267

268

// Limit to 100 connections per second

269

AcceptRateLimit rateLimit = new AcceptRateLimit(100, 1, TimeUnit.SECONDS, connector);

270

server.addBean(rateLimit);

271

272

// Monitor for low resource conditions

273

LowResourceMonitor lowResourceMonitor = new LowResourceMonitor(server);

274

lowResourceMonitor.setMonitoredConnectors(connector);

275

lowResourceMonitor.setMaxMemory(1024 * 1024 * 1024); // 1GB

276

lowResourceMonitor.setMaxConnections(800); // 80% of connection limit

277

server.addBean(lowResourceMonitor);

278

```

279

280

## Low Resource Monitoring

281

282

### LowResourceMonitor

283

284

Monitors server resources and takes action during low resource conditions.

285

286

```java { .api }

287

public class LowResourceMonitor extends ContainerLifeCycle {

288

289

// Constructor

290

public LowResourceMonitor(Server server);

291

292

// Resource thresholds

293

public void setMaxMemory(long maxMemory);

294

public long getMaxMemory();

295

public void setMaxConnections(int maxConnections);

296

public int getMaxConnections();

297

public void setLowResourcesIdleTimeout(long lowResourcesIdleTimeout);

298

public long getLowResourcesIdleTimeout();

299

300

// Monitoring configuration

301

public void setMonitoredConnectors(Connector... connectors);

302

public Collection<Connector> getMonitoredConnectors();

303

public void setMonitorThreads(boolean monitorThreads);

304

public boolean isMonitorThreads();

305

306

// Resource state

307

public boolean isLowOnResources();

308

public String getLowResourcesReasons();

309

}

310

```

311

312

## Connection Metadata

313

314

### ConnectionMetaData Interface

315

316

Provides information about active connections.

317

318

```java { .api }

319

public interface ConnectionMetaData extends Attributes {

320

// Connection identification

321

String getId();

322

323

// Protocol information

324

String getProtocol();

325

HttpConfiguration getHttpConfiguration();

326

327

// Network information

328

SocketAddress getLocalSocketAddress();

329

SocketAddress getRemoteSocketAddress();

330

331

// Security information

332

boolean isSecure();

333

X509Certificate[] getPeerCertificates();

334

}

335

```

336

337

## Advanced Connection Configuration

338

339

### Multiple Protocol Support

340

341

```java

342

// Support HTTP/1.1 and HTTP/2 on same port

343

HttpConfiguration config = new HttpConfiguration();

344

config.setSendServerVersion(false);

345

config.setSendDateHeader(false);

346

347

// HTTP/1.1 factory

348

HttpConnectionFactory http11 = new HttpConnectionFactory(config);

349

350

// HTTP/2 factory

351

HTTP2ServerConnectionFactory http2 = new HTTP2ServerConnectionFactory(config);

352

http2.setMaxConcurrentStreams(128);

353

http2.setInitialStreamRecvWindow(65536);

354

355

// ALPN negotiation factory

356

ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();

357

alpn.setDefaultProtocol("http/1.1");

358

359

// SSL factory with ALPN

360

SslContextFactory.Server sslContextFactory = createSslContextFactory();

361

SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, alpn.getProtocol());

362

363

// Create connector supporting HTTP/1.1 and HTTP/2 over TLS with ALPN

364

ServerConnector connector = new ServerConnector(server, ssl, alpn, http2, http11);

365

connector.setPort(8443);

366

```

367

368

### Custom Connection Factory

369

370

```java

371

public class CustomProtocolConnectionFactory extends AbstractConnectionFactory {

372

373

public CustomProtocolConnectionFactory() {

374

super("custom-protocol");

375

}

376

377

@Override

378

public Connection newConnection(Connector connector, EndPoint endPoint) {

379

return new CustomProtocolConnection(endPoint, connector.getExecutor());

380

}

381

}

382

383

// Custom connection implementation

384

public class CustomProtocolConnection extends AbstractConnection {

385

386

public CustomProtocolConnection(EndPoint endPoint, Executor executor) {

387

super(endPoint, executor);

388

}

389

390

@Override

391

public void onOpen() {

392

super.onOpen();

393

// Initialize custom protocol

394

fillInterested(); // Start reading

395

}

396

397

@Override

398

public void onFillable() {

399

// Handle incoming data for custom protocol

400

ByteBuffer buffer = getByteBufferPool().acquire(1024, false);

401

try {

402

int filled = getEndPoint().fill(buffer);

403

if (filled > 0) {

404

processCustomProtocolData(buffer);

405

}

406

if (filled < 0) {

407

getEndPoint().close();

408

} else {

409

fillInterested(); // Continue reading

410

}

411

} catch (IOException e) {

412

getEndPoint().close(e);

413

} finally {

414

getByteBufferPool().release(buffer);

415

}

416

}

417

418

private void processCustomProtocolData(ByteBuffer buffer) {

419

// Process custom protocol data

420

}

421

}

422

```

423

424

## Connection Statistics and Monitoring

425

426

### Connection Listener

427

428

```java

429

public class ConnectionMonitoringListener implements Connection.Listener {

430

private final AtomicLong connectionsOpened = new AtomicLong();

431

private final AtomicLong connectionsClosed = new AtomicLong();

432

private final Map<String, Long> connectionDurations = new ConcurrentHashMap<>();

433

434

@Override

435

public void onOpened(Connection connection) {

436

connectionsOpened.incrementAndGet();

437

connectionDurations.put(connection.toString(), System.currentTimeMillis());

438

System.out.println("Connection opened: " + connection);

439

}

440

441

@Override

442

public void onClosed(Connection connection) {

443

connectionsClosed.incrementAndGet();

444

Long startTime = connectionDurations.remove(connection.toString());

445

if (startTime != null) {

446

long duration = System.currentTimeMillis() - startTime;

447

System.out.println("Connection closed: " + connection + ", Duration: " + duration + "ms");

448

}

449

}

450

451

public long getConnectionsOpened() {

452

return connectionsOpened.get();

453

}

454

455

public long getConnectionsClosed() {

456

return connectionsClosed.get();

457

}

458

459

public long getActiveConnections() {

460

return connectionsOpened.get() - connectionsClosed.get();

461

}

462

}

463

464

// Usage

465

ConnectionMonitoringListener monitor = new ConnectionMonitoringListener();

466

connector.addBean(monitor);

467

```