Search code examples
javasocketsnioapache-mina

Apache Mina Server and client in java.net.Socket


My application send data to Apache Mina Server which listens with the following configuration..


        IoAcceptor acceptor = new NioSocketAcceptor();
        acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
        //acceptor.getFilterChain().addLast( "logger1", new TempFilter());
        acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
        acceptor.setHandler( new TimeServerHandler() );
        acceptor.getSessionConfig().setReadBufferSize( 2048 );
        acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
        acceptor.bind( new InetSocketAddress(PORT) );

Here's my Client code written in net.Socket


OutputStream oStrm = socket.getOutputStream();
byte[] byteSendBuffer = (requests[clientNo][j]).getBytes(Charset.forName("UTF-8"));


oStrm.write(byteSendBuffer);
oStrm.flush();

Although the logger show message recieved, the server handler's messageRecieved() is never called.. Please hlp.


Solution

  • You are using TextLineCodecFactory as a protocol codec which expects your messages to end with line delimeter. That is "\n" on unix, "\r\n" on windows which can be get by System.lineSeparator() on Java.

    Of course TextLineCodecFactory usability depends on your messages' content. If your message includes line delimeter character in its content, you can not use TextLineCodecFactory. In that case you may want to implement your own codec factory that use special character as delimeter ,fixed sized messages or type-length-value structure.