0

i try to use Apache Mina for my TCP/IP communication. In my case, i have to send long text message like :

0400F23A40010881800200000040000000001623334444555566665000990000005670000725090909999999090909072507306011040001ab9999999999ab9999999999999028000008389999999900000056700036003110000002001000010725090909000000000000000000

But when i try to send it, my TCP Server cannot show the message in console. Here is my Server code :

public class TCPServer {
    private static final int PORT = 3092;

    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"))));
//      

        // Set handler
        acceptor.setHandler(new TimeServerHandler());

        // Set config
        acceptor.getSessionConfig().setMaxReadBufferSize(1048576);
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

        // Bind port
        acceptor.bind(new InetSocketAddress(PORT));
    }
}

And this is my handler

public class TimeServerHandler extends IoHandlerAdapter {
    private static final CharsetEncoder ENCODER = Charset.forName("UTF-8").newEncoder(); 

    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        cause.printStackTrace();
    }

    public void messageReceived(IoSession session, Object message) throws Exception {
        String msg = message.toString();

        if (message instanceof IoBuffer) {
            IoBuffer ioBuffer = IoBuffer.allocate(msg.length(), false).setAutoExpand(true);

            System.out.println(ioBuffer.capacity());
        }

        if (msg.trim().equalsIgnoreCase("quit")) {
            session.close(true);
            return;
        }
    }

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

    }
}

I just to print out capacity, but the server cannot read the message.

How to fix that? Thank you

fanjavaid
  • 1,676
  • 8
  • 34
  • 65

1 Answers1

0

You have to convert it to a String

   if(ioBuffer.isDirect())
    {
        byte[] dst = new byte[ioBuffer.capacity()]
        ioBuffer.get(dst);
        System.out.println(new String(dst, "UTF-8"))
    }
    else
    {
        System.out.println(new String(ioBuffer.array(), "UTF-8"))
    }
Johnny V
  • 795
  • 5
  • 14