by BehindJava

Apache Mina - Simple Client/Server Application

Home » java » Apache Mina - Simple Client/Server Application

In this tutorial we are going to learn about Apache Mina - Simple Client/Server Application in detail with sample code snippet.

Abbrevation for Mina is ‘Multipurpose Infrastructure for Network Applications’, which is a network application framework to develop highly scalable and performant network applications. Let us create a sample mina client server application.

title

Required Jars

mina-core-2.0.7.jar
slf4j-api-1.7.5.jar
slf4j-jdk14-1.7.5.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

package com.sample.timeserver;
 
/**
 * @author behindjava.com
 */
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
 
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
 
public class MinaServer
{
 private static final int PORT = 9999;
 
 public static void main(String[] args) throws IOException
 {
  IoAcceptor acceptor = new NioSocketAcceptor();
 
  acceptor.getFilterChain().addLast("logger", new LoggingFilter());
  acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
 
  acceptor.setHandler(new MinaServerHandler());
  acceptor.getSessionConfig().setReadBufferSize(2048);
  acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
  acceptor.bind(new InetSocketAddress(PORT));
 }
}

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 occurred. The code for the “MinaServerHandler” class is given below,

MinaServerHandler.java

package com.sample.timeserver;
 
/**
 * @author behindjava.com
 */
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
 
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
 
public class MinaServer
{
 private static final int PORT = 9999;
 
 public static void main(String[] args) throws IOException
 {
  IoAcceptor acceptor = new NioSocketAcceptor();
 
  acceptor.getFilterChain().addLast("logger", new LoggingFilter());
  acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
 
  acceptor.setHandler(new MinaServerHandler());
  acceptor.getSessionConfig().setReadBufferSize(2048);
  acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
  acceptor.bind(new InetSocketAddress(PORT));
 }
}

Client part

For the client part “MinaClient” and “MinaClientHandler” class has been used. In the “MinaClient” class the “IoConnector” interface is used to communicate with the server and that fires the event to the handler. Like the server part, The same “LoggingFilter” and “ProtocolCodecFilter” has been used. An interface named “ConnectFuture” is used to windup the asynchronous connection requests.The code for the “MinaClient” class is given below,

MinaClient.java

package com.sample.timeserver;
 
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
 
/**
 * @author behindjava.com
 */
public class MinaClient
{
 private static final int PORT = 9999;
 
 public static void main(String[] args) throws IOException, InterruptedException
 {
  IoConnector connector = new NioSocketConnector();
  connector.getSessionConfig().setReadBufferSize(2048);
 
  connector.getFilterChain().addLast("logger", new LoggingFilter());
  connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
 
  connector.setHandler(new MinaClientHandler("Hello Server"));
  ConnectFuture future = connector.connect(new InetSocketAddress("192.168.1.122", PORT));
  future.awaitUninterruptibly();
 
  if (!future.isConnected())
  {
   return;
  }
  IoSession session = future.getSession();
  session.getConfig().setUseReadOperation(true);
  session.getCloseFuture().awaitUninterruptibly();
  System.out.println(session.read().getMessage());
 
  System.out.println("After Writing");
  connector.dispose();
 
 }
 
}

For the handler, Like the server part the same methods “sessionOpened”, “messageReceived” and “exceptionCaught” has been used. The code for the “MinaClientHandler” class is given below,

MinaClientHandler.java

package com.sample.timeserver;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * @author behindjava.com
 */
public class MinaClientHandler extends IoHandlerAdapter
{
 private final Logger logger = (Logger) LoggerFactory.getLogger(getClass());
 private final String values;
 private boolean finished;
 
 public MinaClientHandler(String values)
 {
  this.values = values;
 }
 
 public boolean isFinished()
 {
  return finished;
 }
 
 @Override
 public void sessionOpened(IoSession session)
 {
  session.write(values);
 }
 
 @Override
 public void messageReceived(IoSession session, Object message)
 {
  logger.info("Message received in the client..");
  logger.info("Message is: " + message.toString());
 }
 
 @Override
 public void exceptionCaught(IoSession session, Throwable cause)
 {
  session.close();
 }
 
}

Now its time to test the preceding codes, First the code “MinaServer” should be executed and then execute the “MinaClient”, the outcome of the codes will looks like the below,

MinaServer - Output

Apr 9, 2013 10:06:52 AM org.apache.mina.filter.logging.LoggingFilter log
INFO: CREATED
Apr 9, 2013 10:06:52 AM org.apache.mina.filter.logging.LoggingFilter log
INFO: OPENED
Apr 9, 2013 10:06:52 AM org.apache.mina.filter.logging.LoggingFilter log
INFO: RECEIVED: HeapBuffer[pos=0 lim=13 cap=2048: 48 65 6C 6C 6F 20 53 65 72 76 65 72 0A]
Apr 9, 2013 10:06:52 AM com.sample.timeserver.MinaServerHandler messageReceived
INFO: Message received in the server..
Apr 9, 2013 10:06:52 AM com.sample.timeserver.MinaServerHandler messageReceived
INFO: Message is: Hello Server
Apr 9, 2013 10:06:52 AM org.apache.mina.filter.logging.LoggingFilter log
INFO: SENT: HeapBuffer[pos=0 lim=0 cap=0: empty]
Apr 9, 2013 10:07:02 AM org.apache.mina.filter.logging.LoggingFilter log
INFO: IDLE
Apr 9, 2013 10:07:02 AM com.sample.timeserver.MinaServerHandler sessionIdle
INFO: Disconnecting the idle.
Apr 9, 2013 10:07:02 AM org.apache.mina.filter.logging.LoggingFilter log
INFO: CLOSED

MinaClient - Output

Apr 9, 2013 10:06:52 AM org.apache.mina.filter.logging.LoggingFilter log
INFO: CREATED
Apr 9, 2013 10:06:52 AM org.apache.mina.filter.logging.LoggingFilter log
INFO: OPENED
Apr 9, 2013 10:06:52 AM org.apache.mina.filter.logging.LoggingFilter log
INFO: SENT: HeapBuffer[pos=0 lim=0 cap=0: empty]
Apr 9, 2013 10:06:52 AM org.apache.mina.filter.logging.LoggingFilter log
INFO: RECEIVED: HeapBuffer[pos=0 lim=7 cap=2048: 72 65 73 75 6C 74 0A]
Apr 9, 2013 10:06:52 AM com.sample.timeserver.MinaClientHandler messageReceived
INFO: Message received in the client..
Apr 9, 2013 10:06:52 AM com.sample.timeserver.MinaClientHandler messageReceived
INFO: Message is: result
Apr 9, 2013 10:07:02 AM org.apache.mina.filter.logging.LoggingFilter log
INFO: CLOSED
result
After Writing