如何使用Apache MINA Server以字节读取二进制数据?

时间:2015-12-30 04:31:52

标签: java client-server serversocket apache-mina mina

这里我正在阅读二进制数据,但这给了我  “java.lang.ClassCastException:java.lang.String无法强制转换为org.apache.mina.core.buffer.IoBuffer”

IoBuffer buffer =(IoBuffer)消息; //此行的异常

IoAcceptor acceptor = new NioSocketAcceptor();

            acceptor.getFilterChain().addLast("logger", new LoggingFilter());
            acceptor.getFilterChain().addLast(
                    "codec",
                    new ProtocolCodecFilter(new TextLineCodecFactory(Charset
                            .forName("ISO-8859-1"))));
    @Override
        public void messageReceived(IoSession session, Object message)
                throws Exception {
    IoBuffer buffer = (IoBuffer) message;
                b = new byte[buffer.remaining()];
                buffer.get(b);
    }

2 个答案:

答案 0 :(得分:1)

此问题为字符串值分配给IOBuffer IoBuffer buffer = (IoBuffer) message;。您无法直接分配。 您必须使用putString方法。我添加了很少的样本。我不知道你在做什么,但这可能对你有帮助。

String message=(String)message;
IoBuffer buf = IoBuffer.allocate(message.length()).setAutoExpand(true);
buf.putString(message, ENCODER);

答案 1 :(得分:0)

我已经完成了这样的事情:

IoAcceptor acceptor = new NioSocketAcceptor();

            acceptor.getFilterChain().addLast("logger", new LoggingFilter());
            acceptor.getFilterChain().addLast(
                    "codec",
                    new ProtocolCodecFilter(new TextLineCodecFactory(Charset
                            .forName("ISO-8859-1"))));
    @Override
        public void messageReceived(IoSession session, Object message)
                throws Exception {
    byte[] b = new byte[100];
    b =  message.toString().getBytes(Charset.forName("ISO-8859-1"));// Read Binary Message
    }