0
# Transport Mechanisms
1
2
Various transport implementations for different communication needs. Transports provide the underlying data transmission layer for Thrift protocols, supporting different communication patterns from simple sockets to HTTP and memory buffers.
3
4
## Capabilities
5
6
### Transport Base Classes
7
8
Core transport interfaces and abstract classes that all transport implementations extend.
9
10
```java { .api }
11
/**
12
* Abstract base class for all transport implementations
13
*/
14
public abstract class TTransport implements Closeable {
15
/** Check if transport is open and ready for operations */
16
public abstract boolean isOpen();
17
18
/** Open the transport connection */
19
public abstract void open() throws TTransportException;
20
21
/** Close the transport connection */
22
public abstract void close();
23
24
/** Read data from transport into buffer */
25
public abstract int read(byte[] buf, int off, int len) throws TTransportException;
26
27
/** Read exactly the specified number of bytes (blocking) */
28
public int readAll(byte[] buf, int off, int len) throws TTransportException;
29
30
/** Write data from buffer to transport */
31
public abstract void write(byte[] buf, int off, int len) throws TTransportException;
32
33
/** Flush any pending writes */
34
public abstract void flush() throws TTransportException;
35
36
// Buffer access methods for buffered transports
37
/** Get internal buffer (may return null for non-buffered) */
38
public byte[] getBuffer();
39
40
/** Get current position in buffer */
41
public int getBufferPosition();
42
43
/** Get remaining bytes in buffer */
44
public int getBytesRemainingInBuffer();
45
46
/** Consume bytes from buffer */
47
public void consumeBuffer(int len);
48
49
/** Peek at buffer data without consuming */
50
public ByteBuffer getByteBuffer(int len);
51
52
/** Utility methods for reading/writing complete byte arrays */
53
public void write(byte[] buf) throws TTransportException;
54
public int read(byte[] buf) throws TTransportException;
55
}
56
57
/**
58
* Factory interface for creating transport instances
59
*/
60
public class TTransportFactory {
61
/** Create transport instance (default: return same transport) */
62
public TTransport getTransport(TTransport trans);
63
}
64
65
/**
66
* Abstract base class for server-side transports
67
*/
68
public abstract class TServerTransport implements Closeable {
69
/** Start listening for connections */
70
public abstract void listen() throws TTransportException;
71
72
/** Accept a new client connection */
73
public abstract TTransport accept() throws TTransportException;
74
75
/** Close the server transport */
76
public abstract void close();
77
78
/** Interrupt any blocking accept() calls */
79
public void interrupt();
80
}
81
82
/**
83
* Base class for endpoint-based transports with host/port information
84
*/
85
public abstract class TEndpointTransport extends TTransport {
86
/** Get host name or address */
87
public abstract String getHost();
88
89
/** Get port number */
90
public abstract int getPort();
91
}
92
```
93
94
### Socket Transports
95
96
Standard TCP socket-based transport implementations for network communication.
97
98
```java { .api }
99
/**
100
* Client-side TCP socket transport
101
*/
102
public class TSocket extends TEndpointTransport {
103
/** Create socket transport to host:port with default timeout */
104
public TSocket(String host, int port) throws TTransportException;
105
106
/** Create socket transport with specific timeout */
107
public TSocket(String host, int port, int timeout) throws TTransportException;
108
109
/** Create socket transport with detailed configuration */
110
public TSocket(TConfiguration config, String host, int port, int socketTimeout, int connectTimeout) throws TTransportException;
111
112
/** Create socket transport wrapping existing socket */
113
public TSocket(Socket socket) throws TTransportException;
114
115
/** Set socket timeout for read operations */
116
public void setTimeout(int timeout);
117
118
/** Set connection timeout for initial connection */
119
public void setConnectTimeout(int timeout);
120
121
/** Set socket timeout (same as setTimeout) */
122
public void setSocketTimeout(int timeout);
123
124
/** Get the underlying socket */
125
public Socket getSocket();
126
127
/** Get host name */
128
public String getHost();
129
130
/** Get port number */
131
public int getPort();
132
133
/** Check if socket is connected */
134
public boolean isOpen();
135
136
/** Open socket connection */
137
public void open() throws TTransportException;
138
139
/** Close socket connection */
140
public void close();
141
}
142
143
/**
144
* Server-side TCP socket transport
145
*/
146
public class TServerSocket extends TServerTransport {
147
/** Create server socket on specified port */
148
public TServerSocket(int port) throws TTransportException;
149
150
/** Create server socket on specified port with timeout */
151
public TServerSocket(int port, int timeout) throws TTransportException;
152
153
/** Create server socket bound to specific address */
154
public TServerSocket(InetSocketAddress bindAddr) throws TTransportException;
155
156
/** Create server socket bound to address with timeout */
157
public TServerSocket(InetSocketAddress bindAddr, int timeout) throws TTransportException;
158
159
/** Create server socket wrapping existing ServerSocket */
160
public TServerSocket(ServerSocket socket) throws TTransportException;
161
162
/** Set accept timeout */
163
public void setTimeout(int timeout);
164
165
/** Get the underlying ServerSocket */
166
public ServerSocket getServerSocket();
167
168
/** Start listening for connections */
169
public void listen() throws TTransportException;
170
171
/** Accept new client connection */
172
public TTransport accept() throws TTransportException;
173
174
/** Close server socket */
175
public void close();
176
}
177
```
178
179
**Usage Examples:**
180
181
```java
182
import org.apache.thrift.transport.TSocket;
183
import org.apache.thrift.transport.TServerSocket;
184
import org.apache.thrift.transport.TTransportException;
185
186
// Client socket with default timeout
187
try {
188
TSocket clientSocket = new TSocket("localhost", 9090);
189
clientSocket.open();
190
// Use socket...
191
clientSocket.close();
192
} catch (TTransportException e) {
193
// Handle connection error
194
}
195
196
// Client socket with custom timeout
197
TSocket timedSocket = new TSocket("remote.example.com", 9090, 5000);
198
199
// Server socket
200
TServerSocket serverSocket = new TServerSocket(9090);
201
serverSocket.listen();
202
while (running) {
203
TTransport clientTransport = serverSocket.accept();
204
// Handle client...
205
}
206
serverSocket.close();
207
```
208
209
### Non-blocking Socket Transports
210
211
Non-blocking socket implementations for high-performance async operations.
212
213
```java { .api }
214
/**
215
* Non-blocking client socket transport using NIO
216
*/
217
public class TNonblockingSocket extends TNonblockingTransport {
218
/** Create non-blocking socket to host:port */
219
public TNonblockingSocket(String host, int port) throws IOException;
220
221
/** Create non-blocking socket with timeout */
222
public TNonblockingSocket(String host, int port, int timeout) throws IOException;
223
224
/** Create non-blocking socket wrapping existing channel */
225
public TNonblockingSocket(SocketChannel socketChannel, int timeout, SelectionKey selectionKey) throws IOException;
226
227
/** Start non-blocking connection */
228
public boolean startConnect() throws IOException;
229
230
/** Complete non-blocking connection */
231
public boolean finishConnect() throws IOException;
232
233
/** Get SelectionKey for this socket */
234
public SelectionKey getSelectionKey();
235
236
/** Get the socket channel */
237
public SocketChannel getSocketChannel();
238
}
239
240
/**
241
* Non-blocking server socket transport using NIO
242
*/
243
public class TNonblockingServerSocket extends TNonblockingServerTransport {
244
/** Create non-blocking server socket on port */
245
public TNonblockingServerSocket(int port) throws TTransportException;
246
247
/** Create non-blocking server socket bound to address */
248
public TNonblockingServerSocket(InetSocketAddress bindAddr) throws TTransportException;
249
250
/** Create non-blocking server socket with specific bind address and client address */
251
public TNonblockingServerSocket(InetSocketAddress bindAddr, InetSocketAddress clientAddr) throws TTransportException;
252
253
/** Register with selector for accept operations */
254
public void registerSelector(Selector selector) throws IOException;
255
256
/** Accept new non-blocking connection */
257
public TNonblockingTransport accept() throws TTransportException;
258
259
/** Get the server socket channel */
260
public ServerSocketChannel getServerSocketChannel();
261
}
262
263
/**
264
* Abstract base class for non-blocking transports
265
*/
266
public abstract class TNonblockingTransport extends TTransport {
267
/** Start non-blocking connect operation */
268
public abstract boolean startConnect() throws IOException;
269
270
/** Complete non-blocking connect operation */
271
public abstract boolean finishConnect() throws IOException;
272
273
/** Get SelectionKey for NIO operations */
274
public abstract SelectionKey getSelectionKey();
275
276
/** Non-blocking read operation */
277
public abstract int read(ByteBuffer buffer) throws IOException;
278
279
/** Non-blocking write operation */
280
public abstract int write(ByteBuffer buffer) throws IOException;
281
}
282
```
283
284
### HTTP Transports
285
286
HTTP-based transport implementations for web services and firewalls.
287
288
```java { .api }
289
/**
290
* HTTP client transport for web services
291
*/
292
public class THttpClient extends TEndpointTransport {
293
/** Create HTTP client for URL */
294
public THttpClient(String url) throws TTransportException;
295
296
/** Create HTTP client for URL with configuration */
297
public THttpClient(String url, TConfiguration config) throws TTransportException;
298
299
/** Create HTTP client for URL object */
300
public THttpClient(URL url) throws TTransportException;
301
302
/** Create HTTP client for URL with configuration */
303
public THttpClient(URL url, TConfiguration config) throws TTransportException;
304
305
/** Set connection timeout */
306
public void setConnectTimeout(int timeout);
307
308
/** Set read timeout */
309
public void setReadTimeout(int timeout);
310
311
/** Set custom HTTP headers */
312
public void setCustomHeaders(Map<String, String> headers);
313
314
/** Set user agent string */
315
public void setUserAgent(String userAgent);
316
317
/** Get URL */
318
public URL getUrl();
319
320
/** Get host from URL */
321
public String getHost();
322
323
/** Get port from URL */
324
public int getPort();
325
}
326
```
327
328
**Usage Examples:**
329
330
```java
331
import org.apache.thrift.transport.THttpClient;
332
import java.util.HashMap;
333
import java.util.Map;
334
335
// Basic HTTP client
336
THttpClient httpClient = new THttpClient("http://api.example.com/thrift");
337
338
// HTTP client with custom headers
339
THttpClient customClient = new THttpClient("https://secure-api.example.com/rpc");
340
Map<String, String> headers = new HashMap<>();
341
headers.put("Authorization", "Bearer " + token);
342
headers.put("X-API-Version", "1.0");
343
customClient.setCustomHeaders(headers);
344
345
// HTTP client with timeouts
346
customClient.setConnectTimeout(5000); // 5 second connect timeout
347
customClient.setReadTimeout(30000); // 30 second read timeout
348
```
349
350
### Memory Transports
351
352
In-memory transport implementations for testing and local communication.
353
354
```java { .api }
355
/**
356
* In-memory transport using byte array buffer
357
*/
358
public class TMemoryBuffer extends TTransport {
359
/** Create memory buffer with initial capacity */
360
public TMemoryBuffer(int size);
361
362
/** Create memory buffer wrapping existing byte array */
363
public TMemoryBuffer(byte[] bytes);
364
365
/** Get current length of data in buffer */
366
public int length();
367
368
/** Get the internal byte array */
369
public byte[] getArray();
370
371
/** Convert buffer contents to string */
372
public String toString(String charset) throws UnsupportedEncodingException;
373
374
/** Clear the buffer */
375
public void clear();
376
377
/** Always returns true (memory buffer is always "open") */
378
public boolean isOpen();
379
380
/** No-op for memory buffer */
381
public void open();
382
383
/** No-op for memory buffer */
384
public void close();
385
}
386
387
/**
388
* Read-only memory transport for existing byte arrays
389
*/
390
public class TMemoryInputTransport extends TTransport {
391
/** Create read-only transport from byte array */
392
public TMemoryInputTransport(byte[] buf);
393
394
/** Create read-only transport from byte array subset */
395
public TMemoryInputTransport(byte[] buf, int offset, int length);
396
397
/** Get number of bytes remaining to read */
398
public int bytesRemainingInBuffer();
399
400
/** Get the buffer */
401
public byte[] getBuffer();
402
403
/** Get current buffer position */
404
public int getBufferPosition();
405
406
/** Reset to beginning of buffer */
407
public void reset();
408
}
409
```
410
411
**Usage Examples:**
412
413
```java
414
import org.apache.thrift.transport.TMemoryBuffer;
415
import org.apache.thrift.transport.TMemoryInputTransport;
416
417
// Create memory buffer for serialization
418
TMemoryBuffer buffer = new TMemoryBuffer(1024);
419
// Serialize object to buffer...
420
byte[] serializedData = buffer.getArray();
421
422
// Create read-only transport from existing data
423
TMemoryInputTransport inputTransport = new TMemoryInputTransport(serializedData);
424
// Deserialize from input transport...
425
426
// Memory buffer for testing
427
TMemoryBuffer testBuffer = new TMemoryBuffer(256);
428
testBuffer.write("test data".getBytes());
429
System.out.println("Buffer contains: " + testBuffer.length() + " bytes");
430
```
431
432
### Stream Transports
433
434
Stream-based transports for file I/O and generic stream operations.
435
436
```java { .api }
437
/**
438
* Transport implementation using input/output streams
439
*/
440
public class TIOStreamTransport extends TTransport {
441
/** Create transport with input and output streams */
442
public TIOStreamTransport(InputStream inputStream, OutputStream outputStream);
443
444
/** Create read-only transport with input stream */
445
public TIOStreamTransport(InputStream inputStream);
446
447
/** Create write-only transport with output stream */
448
public TIOStreamTransport(OutputStream outputStream);
449
450
/** Get the input stream */
451
public InputStream getInputStream();
452
453
/** Get the output stream */
454
public OutputStream getOutputStream();
455
456
/** Always returns true if streams are not null */
457
public boolean isOpen();
458
459
/** No-op (streams should be managed externally) */
460
public void open();
461
462
/** Close the underlying streams */
463
public void close();
464
}
465
466
/**
467
* File-based transport for reading/writing files
468
*/
469
public class TFileTransport extends TTransport {
470
/** Create file transport for reading and/or writing */
471
public TFileTransport(String path, boolean read) throws IOException;
472
473
/** Create file transport with read and append options */
474
public TFileTransport(String path, boolean read, boolean append) throws IOException;
475
476
/** Get the file path */
477
public String getPath();
478
479
/** Check if file is open */
480
public boolean isOpen();
481
482
/** Open the file */
483
public void open() throws TTransportException;
484
485
/** Close the file */
486
public void close();
487
}
488
```
489
490
### Layered Transports
491
492
Transport wrappers that add functionality like framing, compression, and buffering.
493
494
```java { .api }
495
/**
496
* Frame-based transport wrapper that prefixes data with length
497
*/
498
public class TFramedTransport extends TLayeredTransport {
499
/** Default maximum frame size */
500
public static final int DEFAULT_MAX_LENGTH = 16384000;
501
502
/** Create framed transport with default max length */
503
public TFramedTransport(TTransport transport);
504
505
/** Create framed transport with specified max length */
506
public TFramedTransport(TTransport transport, int maxLength);
507
508
/** Clear write buffer without sending */
509
public void clear();
510
511
/** Factory for creating framed transports */
512
public static class Factory extends TTransportFactory {
513
/** Create factory with default max length */
514
public Factory();
515
516
/** Create factory with specified max length */
517
public Factory(int maxLength);
518
519
public TTransport getTransport(TTransport base);
520
}
521
}
522
523
/**
524
* Optimized framed transport with better performance characteristics
525
*/
526
public class TFastFramedTransport extends TLayeredTransport {
527
/** Create fast framed transport with default settings */
528
public TFastFramedTransport(TTransport underlying);
529
530
/** Create fast framed transport with custom buffer sizes */
531
public TFastFramedTransport(TTransport underlying, int initialCapacity, int maxLength);
532
533
/** Factory for creating fast framed transports */
534
public static class Factory extends TTransportFactory {
535
/** Create factory with default settings */
536
public Factory();
537
538
/** Create factory with custom settings */
539
public Factory(int initialCapacity, int maxLength);
540
541
public TTransport getTransport(TTransport base);
542
}
543
}
544
545
/**
546
* Abstract base class for layered transports
547
*/
548
public abstract class TLayeredTransport extends TTransport {
549
/** The underlying transport */
550
protected TTransport transport;
551
552
/** Create layered transport */
553
public TLayeredTransport(TTransport transport);
554
555
/** Get the underlying transport */
556
public TTransport getInnerTransport();
557
}
558
```
559
560
**Usage Examples:**
561
562
```java
563
import org.apache.thrift.transport.TFramedTransport;
564
import org.apache.thrift.transport.TSocket;
565
566
// Create framed transport for message boundaries
567
TSocket socket = new TSocket("localhost", 9090);
568
TFramedTransport framedTransport = new TFramedTransport(socket);
569
570
// Use framed transport factory
571
TFramedTransport.Factory factory = new TFramedTransport.Factory();
572
TTransport clientTransport = factory.getTransport(socket);
573
574
// Fast framed transport with custom buffer size
575
TFastFramedTransport fastFramed = new TFastFramedTransport(socket, 8192, 1024*1024);
576
```
577
578
### SASL Authentication Transports
579
580
Transport implementations with SASL (Simple Authentication and Security Layer) support.
581
582
```java { .api }
583
/**
584
* Client-side SASL transport for authentication
585
*/
586
public class TSaslClientTransport extends TSaslTransport {
587
/** Create SASL client transport */
588
public TSaslClientTransport(String mechanism, String authorizationId, String protocol,
589
String serverName, Map<String, String> props,
590
CallbackHandler cbh, TTransport transport) throws SaslException;
591
592
/** Create SASL client transport with SaslClient */
593
public TSaslClientTransport(SaslClient saslClient, TTransport transport);
594
}
595
596
/**
597
* Server-side SASL transport for authentication
598
*/
599
public class TSaslServerTransport extends TSaslTransport {
600
/** Create SASL server transport */
601
public TSaslServerTransport(String mechanism, String protocol, String serverName,
602
Map<String, String> props, CallbackHandler cbh,
603
TTransport transport) throws SaslException;
604
605
/** Create SASL server transport with SaslServer */
606
public TSaslServerTransport(SaslServer saslServer, TTransport transport);
607
}
608
609
/**
610
* Abstract base class for SASL transports
611
*/
612
public abstract class TSaslTransport extends TLayeredTransport {
613
/** Check if SASL negotiation is complete */
614
public boolean isComplete();
615
616
/** Get negotiated security strength */
617
public String getNegotiatedProperty(String propName);
618
}
619
```
620
621
### Transport Exceptions
622
623
Specific exception types for transport-related errors.
624
625
```java { .api }
626
/**
627
* Exception class for transport-related errors
628
*/
629
public class TTransportException extends TException {
630
public static final int UNKNOWN = 0;
631
public static final int NOT_OPEN = 1;
632
public static final int ALREADY_OPEN = 2;
633
public static final int TIMED_OUT = 3;
634
public static final int END_OF_FILE = 4;
635
public static final int INTERRUPTED = 5;
636
public static final int CORRUPTED_DATA = 6;
637
638
/** Create exception with unknown type */
639
public TTransportException();
640
641
/** Create exception with specific type */
642
public TTransportException(int type);
643
644
/** Create exception with type and message */
645
public TTransportException(int type, String message);
646
647
/** Create exception with message */
648
public TTransportException(String message);
649
650
/** Create exception with type and cause */
651
public TTransportException(int type, Throwable cause);
652
653
/** Create exception with cause */
654
public TTransportException(Throwable cause);
655
656
/** Get the exception type */
657
public int getType();
658
}
659
```
660
661
**Usage Examples for Exception Handling:**
662
663
```java
664
import org.apache.thrift.transport.TTransportException;
665
666
try {
667
transport.open();
668
// Use transport...
669
} catch (TTransportException e) {
670
switch (e.getType()) {
671
case TTransportException.NOT_OPEN:
672
// Handle not open error
673
break;
674
case TTransportException.TIMED_OUT:
675
// Handle timeout
676
break;
677
case TTransportException.END_OF_FILE:
678
// Handle unexpected EOF
679
break;
680
default:
681
// Handle other errors
682
}
683
}
684
```