0
# Core I/O Abstractions
1
2
The core I/O abstractions in Jetty IO provide the fundamental interfaces and base classes for non-blocking network communication, connection management, and protocol handling.
3
4
## Capabilities
5
6
### EndPoint Interface
7
8
The EndPoint interface is the core abstraction for I/O communication, providing both blocking and non-blocking I/O operations.
9
10
```java { .api }
11
/**
12
* Core abstraction for I/O communication using bytes (non-blocking)
13
*/
14
interface EndPoint extends Closeable {
15
/** Read data into buffer, returns number of bytes read or -1 for EOF */
16
int fill(ByteBuffer buffer) throws IOException;
17
18
/** Write data from buffers, returns true if all data was written */
19
boolean flush(ByteBuffer... buffers) throws IOException;
20
21
/** Register callback for async read notification when data is available */
22
void fillInterested(Callback callback) throws ReadPendingException;
23
24
/** Async write operation with callback notification */
25
void write(Callback callback, ByteBuffer... buffers) throws WritePendingException;
26
27
/** Connectionless read operation for UDP-style protocols */
28
SocketAddress receive(ByteBuffer buffer) throws IOException;
29
30
/** Connectionless write operation for UDP-style protocols */
31
boolean send(SocketAddress address, ByteBuffer... buffers) throws IOException;
32
33
/** Check if endpoint is open for I/O operations */
34
boolean isOpen();
35
36
/** Close endpoint with optional cause */
37
void close(Throwable cause);
38
39
/** Shutdown output direction of endpoint */
40
void shutdownOutput();
41
42
/** Check if output is shutdown */
43
boolean isOutputShutdown();
44
45
/** Check if input is shutdown */
46
boolean isInputShutdown();
47
48
/** Get idle timeout in milliseconds */
49
long getIdleTimeout();
50
51
/** Set idle timeout in milliseconds */
52
void setIdleTimeout(long idleTimeout);
53
54
/** Get associated connection */
55
Connection getConnection();
56
57
/** Set associated connection */
58
void setConnection(Connection connection);
59
60
/** Upgrade to new connection, replacing current one */
61
void upgrade(Connection newConnection);
62
63
/** Get local socket address */
64
SocketAddress getLocalSocketAddress();
65
66
/** Get remote socket address */
67
SocketAddress getRemoteSocketAddress();
68
69
/** Get creation timestamp */
70
long getCreatedTimeStamp();
71
72
/** Check if connection is secure (SSL/TLS) */
73
boolean isSecure();
74
75
/** Get SSL session data if available */
76
default SslSessionData getSslSessionData() {
77
return null;
78
}
79
80
/** Get underlying transport object */
81
Object getTransport();
82
83
/** Try to set fill interest without throwing exception */
84
boolean tryFillInterested(Callback callback);
85
86
/** Check if fill interested is currently set */
87
boolean isFillInterested();
88
89
/** Callback for when endpoint is opened */
90
void onOpen();
91
92
/** Callback for when endpoint is closed */
93
void onClose(Throwable cause);
94
95
// Constants
96
SocketAddress EOF = InetSocketAddress.createUnresolved("", 0);
97
98
interface SslSessionData {
99
SSLSession sslSession();
100
String sslSessionId();
101
String cipherSuite();
102
X509Certificate[] peerCertificates();
103
default int keySize() {
104
String cipherSuite = cipherSuite();
105
return cipherSuite == null ? 0 : SslContextFactory.deduceKeyLength(cipherSuite);
106
}
107
}
108
109
interface Wrapper {
110
EndPoint unwrap();
111
}
112
113
interface Pipe {
114
EndPoint getLocalEndPoint();
115
EndPoint getRemoteEndPoint();
116
}
117
}
118
```
119
120
**Usage Examples:**
121
122
```java
123
// Basic I/O operations
124
EndPoint endpoint = // ... obtain endpoint
125
ByteBuffer buffer = ByteBuffer.allocate(1024);
126
127
// Blocking read
128
int bytesRead = endpoint.fill(buffer);
129
if (bytesRead > 0) {
130
buffer.flip();
131
// Process data
132
}
133
134
// Non-blocking write with callback
135
ByteBuffer data = ByteBuffer.wrap("Hello".getBytes());
136
endpoint.write(new Callback() {
137
@Override
138
public void succeeded() {
139
System.out.println("Write completed");
140
}
141
142
@Override
143
public void failed(Throwable x) {
144
System.err.println("Write failed: " + x.getMessage());
145
}
146
}, data);
147
148
// Async read notification
149
endpoint.fillInterested(new Callback() {
150
@Override
151
public void succeeded() {
152
// Data is now available for reading
153
try {
154
ByteBuffer buffer = ByteBuffer.allocate(1024);
155
int bytes = endpoint.fill(buffer);
156
// Process data
157
} catch (IOException e) {
158
failed(e);
159
}
160
}
161
162
@Override
163
public void failed(Throwable x) {
164
System.err.println("Read failed: " + x.getMessage());
165
}
166
});
167
```
168
169
### Connection Interface
170
171
The Connection interface represents a connection associated with an EndPoint for processing I/O events and managing connection lifecycle.
172
173
```java { .api }
174
/**
175
* Connection associated with an EndPoint for processing I/O events
176
*/
177
interface Connection extends Closeable {
178
/** Called when connection is opened */
179
void onOpen();
180
181
/** Called when connection is closed */
182
void onClose(Throwable cause);
183
184
/** Get associated endpoint */
185
EndPoint getEndPoint();
186
187
/** Handle idle timeout expiration, return true if connection should be closed */
188
boolean onIdleExpired(TimeoutException timeoutException);
189
190
/** Get number of messages received */
191
long getMessagesIn();
192
193
/** Get number of messages sent */
194
long getMessagesOut();
195
196
/** Get number of bytes received */
197
long getBytesIn();
198
199
/** Get number of bytes sent */
200
long getBytesOut();
201
202
/** Get connection creation timestamp */
203
long getCreatedTimeStamp();
204
205
/** Add event listener */
206
void addEventListener(EventListener listener);
207
208
/** Remove event listener */
209
void removeEventListener(EventListener listener);
210
211
interface UpgradeFrom {
212
/** Produce unconsumed buffer during protocol upgrade */
213
ByteBuffer onUpgradeFrom();
214
}
215
216
interface UpgradeTo {
217
/** Receive unconsumed buffer during protocol upgrade */
218
void onUpgradeTo(ByteBuffer prefilled);
219
}
220
221
interface Listener extends EventListener {
222
default void onOpened(Connection connection) {}
223
default void onClosed(Connection connection) {}
224
}
225
}
226
```
227
228
**Usage Example:**
229
230
```java
231
public class EchoConnection extends AbstractConnection {
232
public EchoConnection(EndPoint endPoint, Executor executor) {
233
super(endPoint, executor);
234
}
235
236
@Override
237
public void onOpen() {
238
super.onOpen();
239
fillInterested(); // Start reading
240
}
241
242
@Override
243
public void onFillable() {
244
try {
245
ByteBuffer buffer = getByteBufferPool().acquire(1024, false).getByteBuffer();
246
try {
247
int filled = getEndPoint().fill(buffer);
248
if (filled > 0) {
249
buffer.flip();
250
// Echo the data back
251
getEndPoint().write(Callback.NOOP, buffer);
252
} else if (filled < 0) {
253
getEndPoint().close();
254
}
255
} finally {
256
getByteBufferPool().release(buffer);
257
}
258
} catch (IOException e) {
259
close(e);
260
}
261
}
262
}
263
```
264
265
### Abstract Base Classes
266
267
#### AbstractEndPoint
268
269
Base implementation providing common EndPoint functionality.
270
271
```java { .api }
272
abstract class AbstractEndPoint extends AbstractLifeCycle implements EndPoint {
273
protected AbstractEndPoint(Scheduler scheduler);
274
275
// Common endpoint functionality implemented
276
public void close(Throwable cause);
277
public boolean isOpen();
278
public long getCreatedTimeStamp();
279
public void setIdleTimeout(long idleTimeout);
280
public long getIdleTimeout();
281
282
// Template methods for subclasses
283
protected abstract void doClose();
284
protected abstract boolean needsFillInterest();
285
protected abstract void onIncompleteFlush();
286
}
287
```
288
289
#### AbstractConnection
290
291
Base implementation providing common Connection functionality.
292
293
```java { .api }
294
abstract class AbstractConnection extends AbstractLifeCycle implements Connection {
295
protected AbstractConnection(EndPoint endPoint, Executor executor);
296
297
// Common connection functionality
298
public EndPoint getEndPoint();
299
public long getCreatedTimeStamp();
300
public long getMessagesIn();
301
public long getMessagesOut();
302
public long getBytesIn();
303
public long getBytesOut();
304
305
// Utility methods for subclasses
306
protected void fillInterested();
307
protected void fillInterested(Callback callback);
308
protected ByteBufferPool getByteBufferPool();
309
protected Executor getExecutor();
310
311
// Template method for handling readable events
312
public abstract void onFillable();
313
}
314
```
315
316
### Connection Lifecycle Events
317
318
```java { .api }
319
interface Connection.Listener extends EventListener {
320
/** Called when connection is opened */
321
default void onOpened(Connection connection) {}
322
323
/** Called when connection is closed */
324
default void onClosed(Connection connection) {}
325
}
326
```
327
328
### Protocol Upgrade Support
329
330
```java { .api }
331
interface Connection.UpgradeFrom {
332
/**
333
* Produce any unconsumed input during protocol upgrade
334
* @return ByteBuffer containing unconsumed data, or null
335
*/
336
ByteBuffer onUpgradeFrom();
337
}
338
339
interface Connection.UpgradeTo {
340
/**
341
* Receive any unconsumed input during protocol upgrade
342
* @param prefilled ByteBuffer containing unconsumed data from previous protocol
343
*/
344
void onUpgradeTo(ByteBuffer prefilled);
345
}
346
```
347
348
**Protocol Upgrade Example:**
349
350
```java
351
// HTTP/1.1 to HTTP/2 upgrade
352
public class HTTP11Connection extends AbstractConnection implements Connection.UpgradeFrom {
353
@Override
354
public ByteBuffer onUpgradeFrom() {
355
// Return any unprocessed HTTP/1.1 data
356
return unprocessedBuffer;
357
}
358
}
359
360
public class HTTP2Connection extends AbstractConnection implements Connection.UpgradeTo {
361
@Override
362
public void onUpgradeTo(ByteBuffer prefilled) {
363
// Process any data from previous HTTP/1.1 connection
364
if (prefilled != null && prefilled.hasRemaining()) {
365
processPrefilledData(prefilled);
366
}
367
}
368
}
369
370
// Perform upgrade
371
Connection newConnection = new HTTP2Connection(endPoint, executor);
372
endPoint.upgrade(newConnection);
373
```