Mina Server and Client using TCP - BEHIND JAVA

Mina Server and Client using TCP

Share This

Mina Server Architecture

In my previous post i think you got a little bit idea about Mina architecture. Lets come in deep, First off all lets again review the server architecture diagram.

Lets come the code corresponding to above image. Below shows the dependencies needed for mina implementation

        <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
          <modelVersion>4.0.0</modelVersion>
          <groupId>com.behindjava</groupId>
          <artifactId>mina-sample</artifactId>
          <version>0.0.1-SNAPSHOT</version>
          <name>This project contain some mina samples</name>
          
          <dependencies>
          <dependency>
          <groupId>org.apache.mina</groupId>
          <artifactId>mina-core</artifactId>
          <version>2.0.7</version>
         </dependency>
         <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.7.7</version>
         </dependency>
         <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.17</version>
         </dependency>
         
          </dependencies>
        </project>
        

Here you you can find two classes one is TCP Server class and another one is its currosponding handler. The methods in handler invokes asynchronously when a request from any client invokes.

TCP Mina Server class (TCPServer)

        public class TCPServer {
        private static final int PORT = 8084;
        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 TCPServerHandler());
            acceptor.getSessionConfig().setReadBufferSize( 2048 );
            acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
            acceptor.bind( new InetSocketAddress(PORT) );
        }
        }
        

TCP Mina Client Handler Class (TCPServerHandler)

        public class TCPServerHandler  extends IoHandlerAdapter{
         @Override
            public void exceptionCaught( IoSession session, Throwable cause ) throws Exception
            {
                cause.printStackTrace();
            }
            @Override
            public void messageReceived( IoSession session, Object message ) throws Exception
            {
                String str = message.toString();
                
                if( str.trim().equalsIgnoreCase("quit") ) {
                    session.close();
                    return;
                }else{
                 System.out.println(str);
                }
                Date date = new Date();
                session.write( date.toString() );
                System.out.println("Message writtern into server...");
            }
            @Override
            public void sessionIdle( IoSession session, IdleStatus status ) throws Exception
            {
                System.out.println( "IDLE " + session.getIdleCount( status ));
            }
        
        }
        

Check the above code using telnet

The successful running of above code result successful startup on Mina server. You can check the above code using telnet client. By default telnet client is not activated in windows 7. Below follows the steps to activate telnet client in windows 7 machine.

1. For activating the telnet client Goto Control Panel > Programs and Features > Then click on 'Turn windows features on or off'

2. Then activate telnet client and server

3. Then Goto command prompt and type telnet localhost 8084 which result a telnet console

4. Then you can find if you type something in telnet console, then the mina server handle will invoked. From there you can reflect back the changes from messageReceived method

Create Mina Client corresponding to above server implementation

The main difference between mina server and client code implementation is in mina server implementation contains NioSocketAcceptor and in client implementation contains NioSocketConnector instead of that

Mina Client implementation (TCPClient)

        ublic class TCPClient {
         private static final int CONNECT_TIMEOUT = 8084;
         public static void main(String[] args) throws Throwable {
             NioSocketConnector connector = new NioSocketConnector();
             connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
                 connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
             connector.getFilterChain().addLast("logger", new LoggingFilter());
             connector.setHandler(new TCPClientHandler());
             IoSession session;
        
             for (;;) {
                 try {
                     ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 8084));
                     future.awaitUninterruptibly();
                     session = future.getSession();
                     break;
                 } catch (RuntimeIoException e) {
                     System.err.println("Failed to connect.");
                     e.printStackTrace();
                     Thread.sleep(5000);
                 }
             }
        
             // wait until the summation is done
             session.getCloseFuture().awaitUninterruptibly();
             connector.dispose();
         }
        
        }
        

TCP Client Handler implementation (TCPClientHandler)

        public class TCPClientHandler extends IoHandlerAdapter{
               @Override
               public void sessionOpened(IoSession session) {
                   // send summation requests
                String resultString = "Message attach with the client and send to server";
                      session.write(resultString);   
               }
               @Override
               public void messageReceived(IoSession session, Object message) {          
                      // seever returned error code because of overflow, etc.
                System.out.println("Message recived into client...");
                      session.close(true);
                   
               }
               @Override
               public void exceptionCaught(IoSession session, Throwable cause) {
                   session.close(true);
              }
        
        }
        

No comments:

Post a Comment

Pages