0
# Transport Layer
1
2
MINA Core provides multiple transport implementations through a unified API. The transport layer abstracts away the underlying network protocols while providing transport-specific configuration and optimization options.
3
4
## Transport Types
5
6
### NIO Socket Transport (TCP/IP)
7
8
The primary transport for TCP-based network applications using Java NIO.
9
10
#### NioSocketAcceptor
11
12
TCP server implementation:
13
14
```java { .api }
15
// Basic TCP server
16
NioSocketAcceptor acceptor = new NioSocketAcceptor();
17
18
// Multi-threaded configuration
19
NioSocketAcceptor multiThreaded = new NioSocketAcceptor(4); // 4 I/O processors
20
21
// Custom processor configuration
22
IoProcessor<NioSession> processor = new SimpleIoProcessorPool<>(NioProcessor.class, 8);
23
NioSocketAcceptor customProcessors = new NioSocketAcceptor(processor);
24
25
// Custom executor and processor
26
Executor executor = Executors.newCachedThreadPool();
27
NioSocketAcceptor fullCustom = new NioSocketAcceptor(executor, processor);
28
29
// Custom SelectorProvider (advanced)
30
SelectorProvider provider = SelectorProvider.provider();
31
NioSocketAcceptor customSelector = new NioSocketAcceptor(4, provider);
32
```
33
34
#### NioSocketConnector
35
36
TCP client implementation:
37
38
```java { .api }
39
// Basic TCP client
40
NioSocketConnector connector = new NioSocketConnector();
41
42
// Multi-threaded client
43
NioSocketConnector multiThreaded = new NioSocketConnector(2); // 2 I/O processors
44
45
// Custom configuration
46
NioSocketConnector customConnector = new NioSocketConnector(executor, processor);
47
```
48
49
#### Socket Configuration
50
51
```java { .api }
52
// Configure socket-specific settings
53
public void configureTcpSocket(IoService service) {
54
SocketSessionConfig config = (SocketSessionConfig) service.getSessionConfig();
55
56
// Buffer sizes
57
config.setSendBufferSize(64 * 1024); // 64KB send buffer
58
config.setReceiveBufferSize(64 * 1024); // 64KB receive buffer
59
60
// Socket options
61
config.setTcpNoDelay(true); // Disable Nagle algorithm
62
config.setKeepAlive(true); // Enable TCP keep-alive
63
config.setSoLinger(0); // Immediate close (no lingering)
64
config.setReuseAddress(true); // Allow address reuse
65
66
// Traffic class (QoS)
67
config.setTrafficClass(IPTOS_LOWDELAY); // Optimize for low delay
68
69
// Connection timeout (for connectors)
70
if (service instanceof IoConnector) {
71
IoConnector connector = (IoConnector) service;
72
connector.setConnectTimeoutMillis(30000); // 30 second timeout
73
}
74
75
// Acceptor-specific configuration
76
if (service instanceof NioSocketAcceptor) {
77
NioSocketAcceptor acceptor = (NioSocketAcceptor) service;
78
acceptor.setReuseAddress(true);
79
acceptor.setBacklog(100); // Accept queue size
80
}
81
}
82
```
83
84
### NIO Datagram Transport (UDP)
85
86
UDP transport for connectionless communication.
87
88
#### NioDatagramAcceptor
89
90
UDP server implementation:
91
92
```java { .api }
93
// Basic UDP server
94
NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
95
96
// Configure UDP-specific settings
97
DatagramSessionConfig config = acceptor.getSessionConfig();
98
config.setReceiveBufferSize(1024 * 64); // 64KB receive buffer
99
config.setSendBufferSize(1024 * 64); // 64KB send buffer
100
config.setReuseAddress(true);
101
config.setBroadcast(true); // Allow broadcast packets
102
103
// Set up UDP message handler
104
acceptor.setHandler(new UdpServerHandler());
105
106
// Bind to UDP port
107
acceptor.bind(new InetSocketAddress(5000));
108
109
// UDP server handler
110
public class UdpServerHandler extends IoHandlerAdapter {
111
@Override
112
public void messageReceived(IoSession session, Object message) throws Exception {
113
IoBuffer buffer = (IoBuffer) message;
114
115
// Get client address from session
116
SocketAddress clientAddress = session.getRemoteAddress();
117
118
String data = buffer.getString(Charset.forName("UTF-8").newDecoder());
119
System.out.println("Received from " + clientAddress + ": " + data);
120
121
// Echo back to client
122
IoBuffer response = IoBuffer.wrap(("Echo: " + data).getBytes("UTF-8"));
123
session.write(response);
124
}
125
}
126
```
127
128
#### NioDatagramConnector
129
130
UDP client implementation:
131
132
```java { .api }
133
// Basic UDP client
134
NioDatagramConnector connector = new NioDatagramConnector();
135
136
// Configure client settings
137
DatagramSessionConfig config = connector.getSessionConfig();
138
config.setSendBufferSize(1024 * 32); // 32KB send buffer
139
config.setReceiveBufferSize(1024 * 32); // 32KB receive buffer
140
config.setBroadcast(true); // Allow broadcast
141
142
// Set handler
143
connector.setHandler(new UdpClientHandler());
144
145
// Connect to UDP server
146
ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 5000));
147
IoSession session = future.awaitUninterruptibly().getSession();
148
149
// Send UDP message
150
IoBuffer message = IoBuffer.wrap("Hello UDP Server!".getBytes("UTF-8"));
151
session.write(message);
152
153
// UDP client handler
154
public class UdpClientHandler extends IoHandlerAdapter {
155
@Override
156
public void messageReceived(IoSession session, Object message) throws Exception {
157
IoBuffer buffer = (IoBuffer) message;
158
String response = buffer.getString(Charset.forName("UTF-8").newDecoder());
159
System.out.println("Server response: " + response);
160
session.closeNow();
161
}
162
}
163
```
164
165
#### UDP Broadcasting
166
167
```java { .api }
168
public class UdpBroadcaster {
169
170
public void sendBroadcast() throws Exception {
171
NioDatagramConnector connector = new NioDatagramConnector();
172
173
// Enable broadcast
174
DatagramSessionConfig config = connector.getSessionConfig();
175
config.setBroadcast(true);
176
177
connector.setHandler(new IoHandlerAdapter());
178
179
// Connect to broadcast address
180
InetSocketAddress broadcastAddress =
181
new InetSocketAddress("255.255.255.255", 12345);
182
183
ConnectFuture future = connector.connect(broadcastAddress);
184
IoSession session = future.awaitUninterruptibly().getSession();
185
186
// Send broadcast message
187
IoBuffer message = IoBuffer.wrap("Broadcast message".getBytes("UTF-8"));
188
session.write(message);
189
190
session.closeNow();
191
connector.dispose();
192
}
193
194
public void receiveMulticast() throws Exception {
195
NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
196
197
acceptor.setHandler(new IoHandlerAdapter() {
198
@Override
199
public void messageReceived(IoSession session, Object message) throws Exception {
200
IoBuffer buffer = (IoBuffer) message;
201
String data = buffer.getString(Charset.forName("UTF-8").newDecoder());
202
System.out.println("Multicast message: " + data);
203
}
204
});
205
206
// Bind to multicast group
207
InetSocketAddress multicastAddress =
208
new InetSocketAddress("224.0.0.1", 12345);
209
acceptor.bind(multicastAddress);
210
211
// Join multicast group (transport-specific code)
212
// This would require additional configuration at the socket level
213
}
214
}
215
```
216
217
### APR Socket Transport (High-Performance TCP/IP)
218
219
Apache Portable Runtime (APR) based transport for maximum performance on Linux/Unix systems.
220
221
#### APR Requirements
222
223
```java { .api }
224
// Maven dependency for APR transport
225
<dependency>
226
<groupId>org.apache.mina</groupId>
227
<artifactId>mina-transport-apr</artifactId>
228
<version>2.2.4</version>
229
</dependency>
230
231
// System requirements:
232
// - Apache Portable Runtime library (libapr)
233
// - Native APR connector library
234
// - Unix/Linux environment (Windows support limited)
235
```
236
237
#### AprSocketAcceptor
238
239
High-performance TCP server using APR:
240
241
```java { .api }
242
// Basic APR server (requires APR library installed)
243
AprSocketAcceptor acceptor = new AprSocketAcceptor();
244
245
// Multi-threaded APR server
246
AprSocketAcceptor multiThreaded = new AprSocketAcceptor(4); // 4 I/O processors
247
248
// Custom processor configuration
249
IoProcessor<AprSession> processor = new AprIoProcessor(Executors.newCachedThreadPool());
250
AprSocketAcceptor customProcessor = new AprSocketAcceptor(processor);
251
252
// Configure APR-specific settings
253
SocketSessionConfig config = acceptor.getSessionConfig();
254
config.setSendBufferSize(256 * 1024); // 256KB send buffer
255
config.setReceiveBufferSize(256 * 1024); // 256KB receive buffer
256
config.setTcpNoDelay(true); // Disable Nagle algorithm
257
config.setKeepAlive(true); // Enable keep-alive
258
259
// Set handler and bind
260
acceptor.setHandler(new AprServerHandler());
261
acceptor.bind(new InetSocketAddress(8080));
262
263
public class AprServerHandler extends IoHandlerAdapter {
264
@Override
265
public void sessionOpened(IoSession session) throws Exception {
266
System.out.println("APR session opened: " + session.getRemoteAddress());
267
}
268
269
@Override
270
public void messageReceived(IoSession session, Object message) throws Exception {
271
// High-performance message processing
272
IoBuffer buffer = (IoBuffer) message;
273
session.write(buffer); // Echo back
274
}
275
}
276
```
277
278
#### AprSocketConnector
279
280
High-performance TCP client using APR:
281
282
```java { .api }
283
// Basic APR client
284
AprSocketConnector connector = new AprSocketConnector();
285
286
// Configure APR client
287
SocketSessionConfig config = connector.getSessionConfig();
288
config.setConnectTimeoutMillis(10000); // 10 second timeout
289
config.setSendBufferSize(128 * 1024); // 128KB send buffer
290
config.setReceiveBufferSize(128 * 1024); // 128KB receive buffer
291
config.setTcpNoDelay(true); // Low latency
292
293
// Set handler and connect
294
connector.setHandler(new AprClientHandler());
295
ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 8080));
296
IoSession session = future.awaitUninterruptibly().getSession();
297
298
// Send high-performance data
299
IoBuffer message = IoBuffer.allocate(1024);
300
message.putString("APR High Performance Message", Charset.forName("UTF-8"));
301
message.flip();
302
session.write(message);
303
304
public class AprClientHandler extends IoHandlerAdapter {
305
@Override
306
public void messageReceived(IoSession session, Object message) throws Exception {
307
IoBuffer buffer = (IoBuffer) message;
308
System.out.println("APR response: " + buffer.getString(Charset.forName("UTF-8").newDecoder()));
309
}
310
}
311
```
312
313
#### APR Library Configuration
314
315
```java { .api }
316
// Check APR library availability
317
public class AprLibraryChecker {
318
319
public static boolean isAprAvailable() {
320
try {
321
// This will throw exception if APR is not available
322
new AprSocketAcceptor();
323
return true;
324
} catch (Exception e) {
325
System.err.println("APR not available: " + e.getMessage());
326
return false;
327
}
328
}
329
330
public static void printAprInfo() {
331
if (isAprAvailable()) {
332
System.out.println("APR Library: Available");
333
System.out.println("APR provides significantly better performance on Unix/Linux systems");
334
System.out.println("Recommended for high-throughput server applications");
335
} else {
336
System.out.println("APR Library: Not available");
337
System.out.println("Install libapr and native connectors for APR support");
338
System.out.println("Falling back to NIO transport");
339
}
340
}
341
}
342
```
343
344
### Serial Communication Transport
345
346
RS232/COM port communication transport for embedded and hardware interfacing applications.
347
348
#### Serial Transport Requirements
349
350
```java { .api }
351
// Maven dependency for Serial transport
352
<dependency>
353
<groupId>org.apache.mina</groupId>
354
<artifactId>mina-transport-serial</artifactId>
355
<version>2.2.4</version>
356
</dependency>
357
358
// Additional requirement: GNU RXTX library
359
<dependency>
360
<groupId>org.rxtx</groupId>
361
<artifactId>rxtx</artifactId>
362
<version>2.1.7</version>
363
</dependency>
364
365
// System requirements:
366
// - GNU RXTX native library
367
// - Serial port hardware (RS232, USB-to-Serial, etc.)
368
// - Proper permissions for serial port access
369
```
370
371
#### SerialConnector
372
373
Serial port communication (no acceptor - serial ports are point-to-point):
374
375
```java { .api }
376
// Serial port connector
377
SerialConnector connector = new SerialConnector();
378
379
// Configure serial communication parameters
380
SerialSessionConfig config = connector.getSessionConfig();
381
config.setBaudRate(9600); // Common baud rates: 9600, 19200, 38400, 115200
382
config.setDataBits(SerialSessionConfig.DATABITS_8); // 8 data bits
383
config.setStopBits(SerialSessionConfig.STOPBITS_1); // 1 stop bit
384
config.setParity(SerialSessionConfig.PARITY_NONE); // No parity
385
config.setFlowControl(SerialSessionConfig.FLOWCONTROL_NONE); // No flow control
386
387
// Platform-specific port addressing
388
SerialAddress portAddress;
389
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
390
portAddress = new SerialAddress("COM1"); // Windows: COM1, COM2, etc.
391
} else {
392
portAddress = new SerialAddress("/dev/ttyS0"); // Linux: /dev/ttyS0, /dev/ttyUSB0, etc.
393
}
394
395
// Set handler for serial communication
396
connector.setHandler(new SerialHandler());
397
398
// Connect to serial port
399
ConnectFuture future = connector.connect(portAddress);
400
IoSession session = future.awaitUninterruptibly().getSession();
401
402
if (future.isConnected()) {
403
System.out.println("Connected to serial port: " + portAddress);
404
405
// Send command to serial device
406
String command = "AT\r\n"; // Example AT command for modem
407
IoBuffer buffer = IoBuffer.wrap(command.getBytes());
408
session.write(buffer);
409
} else {
410
System.err.println("Failed to connect to serial port: " + future.getException());
411
}
412
413
public class SerialHandler extends IoHandlerAdapter {
414
@Override
415
public void sessionOpened(IoSession session) throws Exception {
416
System.out.println("Serial port opened: " + session.getLocalAddress());
417
418
// Configure session for serial communication
419
session.getConfig().setReadBufferSize(1024); // Small buffer for serial
420
session.getConfig().setIdleTime(IdleStatus.READER_IDLE, 30); // 30 second timeout
421
}
422
423
@Override
424
public void messageReceived(IoSession session, Object message) throws Exception {
425
IoBuffer buffer = (IoBuffer) message;
426
427
// Process serial data (often line-based)
428
byte[] data = new byte[buffer.remaining()];
429
buffer.get(data);
430
String response = new String(data).trim();
431
432
System.out.println("Serial response: " + response);
433
434
// Handle specific serial protocol responses
435
if (response.equals("OK")) {
436
System.out.println("Command acknowledged");
437
} else if (response.startsWith("ERROR")) {
438
System.err.println("Device error: " + response);
439
}
440
}
441
442
@Override
443
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
444
if (cause instanceof SerialPortUnavailableException) {
445
System.err.println("Serial port unavailable: " + cause.getMessage());
446
} else {
447
System.err.println("Serial communication error: " + cause.getMessage());
448
}
449
session.closeNow();
450
}
451
}
452
```
453
454
#### Serial Configuration Options
455
456
```java { .api }
457
public class SerialConfiguration {
458
459
public void configureHighSpeedSerial(SerialConnector connector) {
460
SerialSessionConfig config = connector.getSessionConfig();
461
462
// High-speed configuration
463
config.setBaudRate(115200); // High baud rate
464
config.setDataBits(SerialSessionConfig.DATABITS_8); // 8 data bits
465
config.setStopBits(SerialSessionConfig.STOPBITS_1); // 1 stop bit
466
config.setParity(SerialSessionConfig.PARITY_NONE); // No parity
467
config.setFlowControl(SerialSessionConfig.FLOWCONTROL_RTSCTS); // Hardware flow control
468
469
// Buffer settings for high-speed data
470
config.setReadBufferSize(4096); // Larger buffer for high-speed
471
config.setMinReadBufferSize(512);
472
config.setMaxReadBufferSize(8192);
473
474
// Timeouts for high-speed communication
475
config.setIdleTime(IdleStatus.READER_IDLE, 5); // 5 second read timeout
476
config.setWriteTimeout(3); // 3 second write timeout
477
}
478
479
public void configureModemCommunication(SerialConnector connector) {
480
SerialSessionConfig config = connector.getSessionConfig();
481
482
// Standard modem configuration
483
config.setBaudRate(9600); // Standard modem speed
484
config.setDataBits(SerialSessionConfig.DATABITS_8); // 8 data bits
485
config.setStopBits(SerialSessionConfig.STOPBITS_1); // 1 stop bit
486
config.setParity(SerialSessionConfig.PARITY_NONE); // No parity
487
config.setFlowControl(SerialSessionConfig.FLOWCONTROL_NONE); // No flow control for basic modems
488
489
// Conservative timeouts for slow devices
490
config.setIdleTime(IdleStatus.READER_IDLE, 30); // 30 second timeout
491
config.setWriteTimeout(10); // 10 second write timeout
492
}
493
494
public void configureIndustrialDevice(SerialConnector connector) {
495
SerialSessionConfig config = connector.getSessionConfig();
496
497
// Industrial device configuration (often uses 7 data bits and even parity)
498
config.setBaudRate(19200); // Common industrial speed
499
config.setDataBits(SerialSessionConfig.DATABITS_7); // 7 data bits
500
config.setStopBits(SerialSessionConfig.STOPBITS_1); // 1 stop bit
501
config.setParity(SerialSessionConfig.PARITY_EVEN); // Even parity
502
config.setFlowControl(SerialSessionConfig.FLOWCONTROL_XONXOFF); // Software flow control
503
504
// Robust settings for industrial environment
505
config.setReadBufferSize(256); // Small buffer for simple protocols
506
config.setIdleTime(IdleStatus.READER_IDLE, 60); // 1 minute timeout
507
}
508
}
509
```
510
511
#### Serial Port Discovery
512
513
```java { .api }
514
public class SerialPortDiscovery {
515
516
public static List<String> getAvailableSerialPorts() {
517
List<String> ports = new ArrayList<>();
518
519
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
520
// Windows COM ports
521
for (int i = 1; i <= 20; i++) {
522
String portName = "COM" + i;
523
if (isPortAvailable(portName)) {
524
ports.add(portName);
525
}
526
}
527
} else {
528
// Unix/Linux serial devices
529
String[] commonPorts = {
530
"/dev/ttyS0", "/dev/ttyS1", "/dev/ttyS2", "/dev/ttyS3", // Standard serial
531
"/dev/ttyUSB0", "/dev/ttyUSB1", "/dev/ttyUSB2", // USB-to-Serial
532
"/dev/ttyACM0", "/dev/ttyACM1", // USB CDC devices
533
"/dev/ttyAMA0", "/dev/ttyAMA1" // Raspberry Pi GPIO serial
534
};
535
536
for (String port : commonPorts) {
537
if (isPortAvailable(port)) {
538
ports.add(port);
539
}
540
}
541
}
542
543
return ports;
544
}
545
546
private static boolean isPortAvailable(String portName) {
547
try {
548
SerialConnector connector = new SerialConnector();
549
SerialAddress address = new SerialAddress(portName);
550
551
// Try to connect briefly to test availability
552
ConnectFuture future = connector.connect(address);
553
future.awaitUninterruptibly(1000); // 1 second timeout
554
555
if (future.isConnected()) {
556
future.getSession().closeNow();
557
connector.dispose();
558
return true;
559
}
560
} catch (Exception e) {
561
// Port not available or permission denied
562
}
563
564
return false;
565
}
566
567
public static void printAvailablePorts() {
568
List<String> ports = getAvailableSerialPorts();
569
570
if (ports.isEmpty()) {
571
System.out.println("No serial ports found or accessible");
572
System.out.println("Check RXTX installation and port permissions");
573
} else {
574
System.out.println("Available serial ports:");
575
for (String port : ports) {
576
System.out.println(" " + port);
577
}
578
}
579
}
580
}
581
```
582
583
### VM Pipe Transport (In-Memory)
584
585
High-performance in-memory transport for same-JVM communication.
586
587
#### VmPipeAcceptor
588
589
In-memory server:
590
591
```java { .api }
592
// VM Pipe server
593
VmPipeAcceptor acceptor = new VmPipeAcceptor();
594
595
// No special configuration needed for VM pipes
596
acceptor.setHandler(new VmPipeServerHandler());
597
598
// Bind to VM pipe address (integer port)
599
VmPipeAddress address = new VmPipeAddress(12345);
600
acceptor.bind(address);
601
602
System.out.println("VM Pipe server listening on: " + address);
603
604
public class VmPipeServerHandler extends IoHandlerAdapter {
605
@Override
606
public void messageReceived(IoSession session, Object message) throws Exception {
607
System.out.println("VM Pipe message: " + message);
608
609
// Echo the message back
610
session.write("Echo: " + message);
611
}
612
}
613
```
614
615
#### VmPipeConnector
616
617
In-memory client:
618
619
```java { .api }
620
// VM Pipe client
621
VmPipeConnector connector = new VmPipeConnector();
622
623
connector.setHandler(new VmPipeClientHandler());
624
625
// Connect to VM pipe server
626
VmPipeAddress address = new VmPipeAddress(12345);
627
ConnectFuture future = connector.connect(address);
628
IoSession session = future.awaitUninterruptibly().getSession();
629
630
// Send message through VM pipe
631
session.write("Hello from VM Pipe client!");
632
633
public class VmPipeClientHandler extends IoHandlerAdapter {
634
@Override
635
public void messageReceived(IoSession session, Object message) throws Exception {
636
System.out.println("Server response: " + message);
637
}
638
}
639
```
640
641
#### VM Pipe Performance Example
642
643
```java { .api }
644
// High-performance VM pipe communication
645
public class HighPerformanceVmPipe {
646
647
public void performanceTest() throws Exception {
648
// Server setup
649
VmPipeAcceptor acceptor = new VmPipeAcceptor();
650
acceptor.setHandler(new PerformanceServerHandler());
651
652
VmPipeAddress address = new VmPipeAddress(54321);
653
acceptor.bind(address);
654
655
// Client setup
656
VmPipeConnector connector = new VmPipeConnector();
657
connector.setHandler(new PerformanceClientHandler());
658
659
ConnectFuture future = connector.connect(address);
660
IoSession session = future.awaitUninterruptibly().getSession();
661
662
// Send many messages for performance test
663
long startTime = System.currentTimeMillis();
664
int messageCount = 100000;
665
666
for (int i = 0; i < messageCount; i++) {
667
session.write("Message " + i);
668
}
669
670
// Wait for completion and measure performance
671
Thread.sleep(1000); // Allow processing to complete
672
673
long endTime = System.currentTimeMillis();
674
long duration = endTime - startTime;
675
676
System.out.printf("Sent %d messages in %d ms (%.2f msgs/sec)%n",
677
messageCount, duration, (messageCount * 1000.0 / duration));
678
}
679
680
class PerformanceServerHandler extends IoHandlerAdapter {
681
private AtomicLong messageCount = new AtomicLong();
682
683
@Override
684
public void messageReceived(IoSession session, Object message) throws Exception {
685
// Just count messages, don't echo back for performance
686
long count = messageCount.incrementAndGet();
687
if (count % 10000 == 0) {
688
System.out.println("Processed " + count + " messages");
689
}
690
}
691
}
692
693
class PerformanceClientHandler extends IoHandlerAdapter {
694
// Minimal client handler for performance testing
695
}
696
}
697
```
698
699
## Transport Metadata
700
701
### Getting Transport Information
702
703
```java { .api }
704
public class TransportInfoExample {
705
706
public void printTransportInfo(IoService service) {
707
TransportMetadata metadata = service.getTransportMetadata();
708
709
System.out.println("Transport Provider: " + metadata.getProviderName());
710
System.out.println("Transport Name: " + metadata.getName());
711
System.out.println("Connection Model: " + metadata.getConnectionModel());
712
System.out.println("Session Config Type: " + metadata.getSessionConfigType().getName());
713
System.out.println("Session Type: " + metadata.getSessionType().getName());
714
System.out.println("Address Type: " + metadata.getAddressType().getName());
715
System.out.println("Envelope Support: " + metadata.hasFragmentation());
716
System.out.println("Fragmentation Support: " + metadata.hasFragmentation());
717
}
718
719
public void selectTransportBasedOnMetadata(IoService service) {
720
TransportMetadata metadata = service.getTransportMetadata();
721
722
if (metadata.getConnectionModel() == ConnectionModel.CONNECTION) {
723
System.out.println("Connection-oriented transport (TCP)");
724
// Configure for reliable delivery
725
configureReliableTransport(service);
726
} else if (metadata.getConnectionModel() == ConnectionModel.CONNECTIONLESS) {
727
System.out.println("Connectionless transport (UDP)");
728
// Configure for fast delivery
729
configureFastTransport(service);
730
}
731
732
if (metadata.hasFragmentation()) {
733
System.out.println("Transport supports fragmentation");
734
// Can send large messages
735
} else {
736
System.out.println("Transport requires message size management");
737
// Need to fragment messages manually
738
}
739
}
740
}
741
```
742
743
## Transport-Specific Session Configuration
744
745
### Socket Session Configuration
746
747
```java { .api }
748
public class SocketSessionConfiguration {
749
750
public void configureSocketSession(SocketSessionConfig config) {
751
// Buffer configuration
752
config.setSendBufferSize(128 * 1024); // 128KB send buffer
753
config.setReceiveBufferSize(128 * 1024); // 128KB receive buffer
754
755
// Socket behavior
756
config.setTcpNoDelay(true); // Disable Nagle's algorithm
757
config.setKeepAlive(true); // Enable keep-alive
758
config.setSoLinger(-1); // Default linger behavior
759
config.setReuseAddress(true); // Allow port reuse
760
761
// Traffic control
762
config.setTrafficClass(IPTOS_LOWDELAY | IPTOS_THROUGHPUT);
763
764
// Session-level settings
765
config.setReadBufferSize(8192); // MINA read buffer
766
config.setMinReadBufferSize(1024); // Minimum buffer size
767
config.setMaxReadBufferSize(65536); // Maximum buffer size
768
769
// Idle time settings
770
config.setIdleTime(IdleStatus.READER_IDLE, 60); // 60 seconds
771
config.setIdleTime(IdleStatus.WRITER_IDLE, 30); // 30 seconds
772
config.setIdleTime(IdleStatus.BOTH_IDLE, 90); // 90 seconds
773
774
// Write timeout
775
config.setWriteTimeout(10); // 10 seconds write timeout
776
777
// Throughput calculation
778
config.setThroughputCalculationInterval(3); // Calculate every 3 seconds
779
}
780
}
781
```
782
783
### Datagram Session Configuration
784
785
```java { .api }
786
public class DatagramSessionConfiguration {
787
788
public void configureDatagramSession(DatagramSessionConfig config) {
789
// Buffer sizes (important for UDP)
790
config.setSendBufferSize(256 * 1024); // 256KB send buffer
791
config.setReceiveBufferSize(256 * 1024); // 256KB receive buffer
792
793
// UDP-specific options
794
config.setBroadcast(true); // Allow broadcast packets
795
config.setReuseAddress(true); // Allow address reuse
796
797
// Traffic class for QoS
798
config.setTrafficClass(IPTOS_LOWDELAY); // Optimize for low latency
799
800
// Close session immediately after idle (UDP is stateless)
801
config.setCloseOnPortUnreachable(true); // Close on ICMP port unreachable
802
803
// Session settings
804
config.setReadBufferSize(1500); // MTU-sized buffer
805
config.setMinReadBufferSize(512); // Minimum for small packets
806
config.setMaxReadBufferSize(65507); // Maximum UDP payload
807
808
// Idle detection (less useful for UDP)
809
config.setIdleTime(IdleStatus.BOTH_IDLE, 300); // 5 minutes
810
}
811
}
812
```
813
814
### VM Pipe Session Configuration
815
816
```java { .api }
817
public class VmPipeSessionConfiguration {
818
819
public void configureVmPipeSession(VmPipeSessionConfig config) {
820
// VM Pipe has minimal configuration since it's in-memory
821
822
// Buffer settings (can be larger since no network overhead)
823
config.setReadBufferSize(64 * 1024); // 64KB read buffer
824
config.setMinReadBufferSize(4096); // 4KB minimum
825
config.setMaxReadBufferSize(1024 * 1024); // 1MB maximum
826
827
// No network timeouts needed, but can set for application logic
828
config.setIdleTime(IdleStatus.BOTH_IDLE, 3600); // 1 hour
829
830
// Throughput calculation (very fast for in-memory)
831
config.setThroughputCalculationInterval(1); // Every second
832
}
833
}
834
```
835
836
## Advanced Transport Configuration
837
838
### Custom Socket Channel Configuration
839
840
```java { .api }
841
public class AdvancedSocketConfiguration {
842
843
public void configureAdvancedSocket(NioSocketAcceptor acceptor) throws IOException {
844
// Access underlying socket channel configuration
845
acceptor.setReuseAddress(true);
846
acceptor.setBacklog(1000); // Large accept queue for high load
847
848
// Custom session configuration
849
SocketSessionConfig config = acceptor.getSessionConfig();
850
851
// Performance tuning
852
config.setSendBufferSize(1024 * 1024); // 1MB send buffer
853
config.setReceiveBufferSize(1024 * 1024); // 1MB receive buffer
854
config.setTcpNoDelay(true); // Immediate send
855
856
// Advanced socket options (require casting to implementation)
857
if (config instanceof NioSocketSessionConfig) {
858
NioSocketSessionConfig nioConfig = (NioSocketSessionConfig) config;
859
860
// Set socket options directly
861
nioConfig.setAll(config.getAll());
862
}
863
}
864
865
public void configureServerSocketOptions(NioSocketAcceptor acceptor) {
866
// Configure acceptor for high-performance server
867
868
// Use multiple I/O processors for CPU cores
869
int processors = Runtime.getRuntime().availableProcessors();
870
NioSocketAcceptor multiCoreAcceptor = new NioSocketAcceptor(processors);
871
872
// Set large backlog for connection bursts
873
multiCoreAcceptor.setBacklog(2000);
874
875
// Enable address reuse for quick restart
876
multiCoreAcceptor.setReuseAddress(true);
877
878
// Configure session defaults
879
SocketSessionConfig config = multiCoreAcceptor.getSessionConfig();
880
config.setSendBufferSize(256 * 1024); // 256KB
881
config.setReceiveBufferSize(256 * 1024); // 256KB
882
config.setTcpNoDelay(true); // Low latency
883
config.setKeepAlive(true); // Detect dead connections
884
}
885
}
886
```
887
888
### Transport Selection Strategy
889
890
```java { .api }
891
public class TransportSelector {
892
893
public IoAcceptor selectAcceptor(String protocol, Map<String, Object> properties) {
894
switch (protocol.toLowerCase()) {
895
case "tcp":
896
case "socket":
897
return createTcpAcceptor(properties);
898
899
case "udp":
900
case "datagram":
901
return createUdpAcceptor(properties);
902
903
case "pipe":
904
case "vmpipe":
905
return createVmPipeAcceptor(properties);
906
907
default:
908
throw new IllegalArgumentException("Unsupported protocol: " + protocol);
909
}
910
}
911
912
private IoAcceptor createTcpAcceptor(Map<String, Object> properties) {
913
int processors = (Integer) properties.getOrDefault("processors",
914
Runtime.getRuntime().availableProcessors());
915
916
NioSocketAcceptor acceptor = new NioSocketAcceptor(processors);
917
918
// Configure based on properties
919
if (properties.containsKey("backlog")) {
920
acceptor.setBacklog((Integer) properties.get("backlog"));
921
}
922
923
SocketSessionConfig config = acceptor.getSessionConfig();
924
925
if (properties.containsKey("sendBufferSize")) {
926
config.setSendBufferSize((Integer) properties.get("sendBufferSize"));
927
}
928
929
if (properties.containsKey("receiveBufferSize")) {
930
config.setReceiveBufferSize((Integer) properties.get("receiveBufferSize"));
931
}
932
933
Boolean tcpNoDelay = (Boolean) properties.get("tcpNoDelay");
934
if (tcpNoDelay != null) {
935
config.setTcpNoDelay(tcpNoDelay);
936
}
937
938
return acceptor;
939
}
940
941
private IoAcceptor createUdpAcceptor(Map<String, Object> properties) {
942
NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
943
944
DatagramSessionConfig config = acceptor.getSessionConfig();
945
946
if (properties.containsKey("broadcast")) {
947
config.setBroadcast((Boolean) properties.get("broadcast"));
948
}
949
950
if (properties.containsKey("sendBufferSize")) {
951
config.setSendBufferSize((Integer) properties.get("sendBufferSize"));
952
}
953
954
if (properties.containsKey("receiveBufferSize")) {
955
config.setReceiveBufferSize((Integer) properties.get("receiveBufferSize"));
956
}
957
958
return acceptor;
959
}
960
961
private IoAcceptor createVmPipeAcceptor(Map<String, Object> properties) {
962
VmPipeAcceptor acceptor = new VmPipeAcceptor();
963
964
// VM pipe has minimal configuration
965
VmPipeSessionConfig config =
966
(VmPipeSessionConfig) acceptor.getSessionConfig();
967
968
if (properties.containsKey("readBufferSize")) {
969
config.setReadBufferSize((Integer) properties.get("readBufferSize"));
970
}
971
972
return acceptor;
973
}
974
}
975
```
976
977
The transport layer in MINA Core provides flexible and high-performance networking capabilities across TCP, UDP, and in-memory communication channels, with comprehensive configuration options for different use cases and performance requirements.