Tuesday, June 5, 2012

Apache Mina Simple client and Server Application

Introduction
Abbrevation for Mina is ‘Multipurpose Infrastructure for Network Applications’, which is a network application framework to develop highly scalable and performant network applications. In this article, let us see how to create a simple client/server application using Apache Mina 2.0.x.
Required jars

  1. Apache Mina 2.0.x jars
  2. slf4j-api.jar
  3. slf4k-jdk14.jar
Server part
For the server part, Two classes named “MinaServer” and “MinaServerHandler” has been used. The “MinaServer” class contains a main method and an interface named “IoAcceptor” is used to accept the incoming connections from the client and that fires the event to the handler. Two filters has been used, the first one is the “LoggingFilter” which logs all the events and requests and the second one is the “ProtocolCodecFilter” which is used to convert an incoming ByteBuffer into message POJO. The code for the “MinaServer” class is given below,

MinaServer.java
01package com.sample.timeserver;
02
03/**
04* @author giftsam
05*/
06import java.io.IOException;
07import java.net.InetSocketAddress;
08import java.nio.charset.Charset;
09
10import org.apache.mina.core.session.IdleStatus;
11import org.apache.mina.core.service.IoAcceptor;
12import org.apache.mina.filter.codec.ProtocolCodecFilter;
13import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
14import org.apache.mina.filter.logging.LoggingFilter;
15import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
16
17public class MinaServer
18{
19private static final int PORT = 1234;
20
21public static void main(String[] args) throws IOException
22{
23IoAcceptor acceptor = new NioSocketAcceptor();
24
25acceptor.getFilterChain().addLast("logger", new LoggingFilter());
26acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
27
28acceptor.setHandler(new MinaServerHandler());
29acceptor.getSessionConfig().setReadBufferSize(2048);
30acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
31acceptor.bind(new InetSocketAddress(PORT));
32}
33}
Next let us create a custom handler named “MinaServerHandler”, which contains four methods. The first method “sessionOpened” is called when the session is opened and it is used to set the session idle time. The second method “receiveMessage” is used to receive the message sent by the client. The other two methods “sessionIdle” is used to close the session when it was idle for 10 secs and the fourth method “exceptionCaught” is used to close the session when an exception occured. The code for the “MinaServerHandler” class is given below,
MinaServerHandler.java
01package com.sample.timeserver;
02import org.apache.mina.core.session.IdleStatus;
03import org.apache.mina.core.service.IoHandlerAdapter;
04import org.apache.mina.core.session.IoSession;
05import org.slf4j.Logger;
06import org.slf4j.LoggerFactory;
07
08/**
09* @author giftsam
10*/
11public class MinaServerHandler extends IoHandlerAdapter
12{
13private final Logger logger = (Logger) LoggerFactory.getLogger(getClass());
14
15@Override
16public void sessionOpened(IoSession session)
17{
18// set idle time to 10 seconds
19session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
20
21session.setAttribute("Values: ");
22}
23
24@Override
25public void messageReceived(IoSession session, Object message)
26{
27logger.info("Message received in the server..");
28logger.info("Message is: " + message.toString());
29}
30
31@Override
32public void sessionIdle(IoSession session, IdleStatus status)
33{
34logger.info("Disconnecting the idle.");
35// disconnect an idle client
36session.close();
37}
38
39@Override
40public void exceptionCaught(IoSession session, Throwable cause)
41{
42// close the connection on exceptional situation
43session.close();
44}
45
46}