or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdbuffer-management.mdfilter-chain.mdindex.mdprotocol-codecs.mdservice-abstractions.mdsession-management.mdtransport-layer.md

index.mddocs/

0

# Apache MINA Core 2.2.4

1

2

Apache MINA Core is a network application framework that helps developers create high-performance and scalable network applications. It provides a unified API for various transports such as TCP/IP and UDP/IP via Java NIO.

3

4

## Package Information

5

6

**Maven Dependency:**

7

```xml

8

<dependency>

9

<groupId>org.apache.mina</groupId>

10

<artifactId>mina-core</artifactId>

11

<version>2.2.4</version>

12

</dependency>

13

```

14

15

**Java Requirements:** Java 8+

16

17

## Core Imports

18

19

```java { .api }

20

// Core service abstractions

21

import org.apache.mina.core.service.IoAcceptor;

22

import org.apache.mina.core.service.IoConnector;

23

import org.apache.mina.core.service.IoHandler;

24

import org.apache.mina.core.service.IoHandlerAdapter;

25

26

// Session management

27

import org.apache.mina.core.session.IoSession;

28

import org.apache.mina.core.session.IoSessionConfig;

29

30

// Transport implementations

31

import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

32

import org.apache.mina.transport.socket.nio.NioSocketConnector;

33

import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;

34

import org.apache.mina.transport.socket.nio.NioDatagramConnector;

35

36

// Filters and filter chain

37

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;

38

import org.apache.mina.filter.codec.ProtocolCodecFilter;

39

import org.apache.mina.filter.logging.LoggingFilter;

40

41

// Async operations

42

import org.apache.mina.core.future.ConnectFuture;

43

import org.apache.mina.core.future.WriteFuture;

44

45

// Buffer management

46

import org.apache.mina.core.buffer.IoBuffer;

47

48

// Network addresses

49

import java.net.InetSocketAddress;

50

```

51

52

## Basic Usage

53

54

### Creating a TCP Server

55

56

```java { .api }

57

// Create acceptor for incoming connections

58

IoAcceptor acceptor = new NioSocketAcceptor();

59

60

// Add logging filter for debugging

61

acceptor.getFilterChain().addLast("logger", new LoggingFilter());

62

63

// Set the handler that will process incoming messages

64

acceptor.setHandler(new IoHandlerAdapter() {

65

@Override

66

public void sessionOpened(IoSession session) throws Exception {

67

System.out.println("Session opened: " + session.getRemoteAddress());

68

}

69

70

@Override

71

public void messageReceived(IoSession session, Object message) throws Exception {

72

// Echo received message back to client

73

session.write(message);

74

}

75

76

@Override

77

public void exceptionCaught(IoSession session, Throwable cause) throws Exception {

78

cause.printStackTrace();

79

session.closeNow();

80

}

81

});

82

83

// Bind to port 8080 and start accepting connections

84

acceptor.bind(new InetSocketAddress(8080));

85

System.out.println("Server started on port 8080");

86

```

87

88

### Creating a TCP Client

89

90

```java { .api }

91

// Create connector for outgoing connections

92

IoConnector connector = new NioSocketConnector();

93

94

// Add logging filter

95

connector.getFilterChain().addLast("logger", new LoggingFilter());

96

97

// Set the handler for client-side processing

98

connector.setHandler(new IoHandlerAdapter() {

99

@Override

100

public void sessionOpened(IoSession session) throws Exception {

101

System.out.println("Connected to server");

102

// Send a message to the server

103

session.write(IoBuffer.wrap("Hello Server!".getBytes()));

104

}

105

106

@Override

107

public void messageReceived(IoSession session, Object message) throws Exception {

108

IoBuffer buffer = (IoBuffer) message;

109

System.out.println("Received: " + new String(buffer.array()));

110

session.closeNow();

111

}

112

});

113

114

// Connect to the server

115

ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 8080));

116

future.awaitUninterruptibly();

117

118

if (future.isConnected()) {

119

System.out.println("Connection established");

120

IoSession session = future.getSession();

121

// Session is ready for communication

122

}

123

```

124

125

## Architecture

126

127

Apache MINA Core follows a modular, filter-based architecture:

128

129

```

130

Application Layer

131

132

IoHandler

133

134

Filter Chain → [Filter1] → [Filter2] → [CodecFilter] → [LoggingFilter]

135

136

IoService (Acceptor/Connector)

137

138

IoSession

139

140

Transport Layer (TCP/UDP/VM Pipe)

141

```

142

143

### Key Components:

144

145

- **IoService**: Base abstraction for acceptors and connectors

146

- **IoSession**: Represents a connection between two endpoints

147

- **IoHandler**: Application logic for handling I/O events

148

- **IoFilter**: Intercepts and processes I/O events (similar to servlet filters)

149

- **IoBuffer**: MINA's enhanced ByteBuffer implementation

150

- **Transport**: Pluggable transport implementations (NIO Socket, Datagram, VM Pipe)

151

152

## Capabilities

153

154

### [Session Management](session-management.md)

155

156

Comprehensive session lifecycle management with attributes and idle detection:

157

158

```java { .api }

159

// Session lifecycle events

160

public class SessionHandler extends IoHandlerAdapter {

161

@Override

162

public void sessionCreated(IoSession session) throws Exception {

163

// Set session attributes

164

session.setAttribute("startTime", System.currentTimeMillis());

165

}

166

167

@Override

168

public void sessionOpened(IoSession session) throws Exception {

169

// Configure session-specific settings

170

session.getConfig().setReadBufferSize(2048);

171

session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

172

}

173

174

@Override

175

public void sessionIdle(IoSession session, IdleStatus status) throws Exception {

176

// Handle idle sessions (timeout management)

177

if (status == IdleStatus.BOTH_IDLE) {

178

session.closeNow();

179

}

180

}

181

}

182

```

183

184

### [Service Abstractions](service-abstractions.md)

185

186

Unified API for acceptors and connectors with comprehensive lifecycle management:

187

188

```java { .api }

189

// Acceptor configuration and management

190

NioSocketAcceptor acceptor = new NioSocketAcceptor();

191

acceptor.setReuseAddress(true);

192

acceptor.getSessionConfig().setReadBufferSize(2048);

193

acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

194

195

// Bind to multiple addresses

196

acceptor.bind(new InetSocketAddress(8080));

197

acceptor.bind(new InetSocketAddress(8443));

198

199

// Service statistics and management

200

IoServiceStatistics stats = acceptor.getStatistics();

201

long totalSessions = stats.getCumulativeManagedSessionCount();

202

```

203

204

### [Filter Chain](filter-chain.md)

205

206

Powerful filter-based processing pipeline for request/response handling:

207

208

```java { .api }

209

// Building filter chains

210

DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();

211

212

// Add built-in filters

213

chain.addLast("ssl", new SslFilter(sslContext));

214

chain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory()));

215

chain.addLast("logger", new LoggingFilter());

216

chain.addLast("executor", new ExecutorFilter());

217

218

// Custom filter implementation

219

public class CustomFilter extends IoFilterAdapter {

220

@Override

221

public void messageReceived(NextFilter nextFilter, IoSession session, Object message)

222

throws Exception {

223

// Pre-process message

224

String processed = preProcess((String) message);

225

nextFilter.messageReceived(session, processed);

226

}

227

}

228

```

229

230

### [Transport Layer](transport-layer.md)

231

232

Multiple transport implementations with consistent API:

233

234

```java { .api }

235

// TCP/IP Socket transport

236

NioSocketAcceptor tcpAcceptor = new NioSocketAcceptor();

237

NioSocketConnector tcpConnector = new NioSocketConnector();

238

239

// UDP Datagram transport

240

NioDatagramAcceptor udpAcceptor = new NioDatagramAcceptor();

241

NioDatagramConnector udpConnector = new NioDatagramConnector();

242

243

// APR Socket transport (high-performance, requires APR library)

244

AprSocketAcceptor aprAcceptor = new AprSocketAcceptor();

245

AprSocketConnector aprConnector = new AprSocketConnector();

246

247

// Serial Communication transport (RS232/COM ports)

248

SerialConnector serialConnector = new SerialConnector();

249

250

// VM Pipe (in-memory) transport

251

VmPipeAcceptor pipeAcceptor = new VmPipeAcceptor();

252

VmPipeConnector pipeConnector = new VmPipeConnector();

253

254

// Transport-specific configuration

255

SocketSessionConfig socketConfig = tcpAcceptor.getSessionConfig();

256

socketConfig.setSendBufferSize(64 * 1024);

257

socketConfig.setTcpNoDelay(true);

258

```

259

260

### [Buffer Management](buffer-management.md)

261

262

Advanced buffer operations with auto-expansion and pooling:

263

264

```java { .api }

265

// Creating and manipulating IoBuffers

266

IoBuffer buffer = IoBuffer.allocate(1024);

267

buffer.setAutoExpand(true);

268

buffer.setAutoShrink(true);

269

270

// Writing data

271

buffer.putString("Hello", Charset.forName("UTF-8"));

272

buffer.putInt(42);

273

274

// Reading data

275

buffer.flip();

276

String message = buffer.getString(Charset.forName("UTF-8").newDecoder());

277

int number = buffer.getInt();

278

279

// Buffer utilities

280

String hexDump = buffer.getHexDump();

281

IoBuffer duplicate = buffer.duplicate();

282

```

283

284

### [Async Operations](async-operations.md)

285

286

Comprehensive Future-based asynchronous operations:

287

288

```java { .api }

289

// Asynchronous connection

290

ConnectFuture connectFuture = connector.connect(address);

291

connectFuture.addListener(new IoFutureListener<ConnectFuture>() {

292

@Override

293

public void operationComplete(ConnectFuture future) {

294

if (future.isConnected()) {

295

IoSession session = future.getSession();

296

// Handle successful connection

297

} else {

298

// Handle connection failure

299

Throwable cause = future.getException();

300

}

301

}

302

});

303

304

// Asynchronous write operations

305

WriteFuture writeFuture = session.write(message);

306

writeFuture.awaitUninterruptibly();

307

if (writeFuture.isWritten()) {

308

// Message sent successfully

309

}

310

```

311

312

### [Protocol Codecs](protocol-codecs.md)

313

314

Flexible codec system for message encoding/decoding:

315

316

```java { .api }

317

// Text line protocol codec

318

TextLineCodecFactory codecFactory = new TextLineCodecFactory(

319

Charset.forName("UTF-8"),

320

LineDelimiter.CRLF,

321

LineDelimiter.LF

322

);

323

324

// Object serialization codec

325

ObjectSerializationCodecFactory objectCodec = new ObjectSerializationCodecFactory();

326

327

// Adding codec to filter chain

328

filterChain.addLast("codec", new ProtocolCodecFilter(codecFactory));

329

330

// Custom codec implementation

331

public class CustomCodecFactory implements ProtocolCodecFactory {

332

@Override

333

public ProtocolEncoder getEncoder(IoSession session) throws Exception {

334

return new CustomEncoder();

335

}

336

337

@Override

338

public ProtocolDecoder getDecoder(IoSession session) throws Exception {

339

return new CustomDecoder();

340

}

341

}

342

```

343

344

## Error Handling

345

346

```java { .api }

347

// Comprehensive error handling in IoHandler

348

public class RobustHandler extends IoHandlerAdapter {

349

@Override

350

public void exceptionCaught(IoSession session, Throwable cause) throws Exception {

351

if (cause instanceof IOException) {

352

// Handle I/O errors

353

LOGGER.warn("I/O error on session {}: {}", session.getId(), cause.getMessage());

354

} else if (cause instanceof ProtocolCodecException) {

355

// Handle codec errors

356

LOGGER.error("Protocol error on session {}: {}", session.getId(), cause.getMessage());

357

} else {

358

// Handle unexpected errors

359

LOGGER.error("Unexpected error on session " + session.getId(), cause);

360

}

361

362

// Close session on critical errors

363

session.closeNow();

364

}

365

}

366

```

367

368

Apache MINA Core provides a robust foundation for building networked applications with its clean abstractions, powerful filtering system, and comprehensive async I/O support.