解决方案 »

  1.   

    其他Codec有好多种。一般,区分逻辑包有这么几种方式:1 使用特殊字符(字节)作为分割符,比如你现在用的换行符。这种方式,要么分隔符不会出现在正文里面,要么规定好转义方式
    2 在包头使用长度位,从包头开始N字节,是一个逻辑包。所以,你选用的编码/解码,要配对的,编码时候,换行不是正文,那么你解码的地方,也要做相应处理。
      

  2.   

    要达到我想要的结果,使用哪种codec才合适呢,其实使用的就是TextLineCodecFactory这个类的编码/解码,我想用换行做为分隔符,除了使用TextLineCodecFactory,还有别的类可使用吗,如果编写自己的filter,你能写一份吗?
      

  3.   

    IoAcceptor acceptor = new NioSocketAcceptor();
    acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ProtocolCodecFactory() { @Override
    public ProtocolEncoder getEncoder(IoSession arg0) throws Exception { ProtocolEncoderAdapter p = new ProtocolEncoderAdapter() { @Override
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    System.out.println(message);
    if(message instanceof String){
    IoBuffer buffer = IoBuffer.wrap(((String)message).getBytes());
    buffer.position(((String)message).getBytes().length);
    buffer.flip();
    out.write(buffer);
    }
    out.flush();
    }
    }; return p;
    } @Override
    public ProtocolDecoder getDecoder(IoSession arg0) throws Exception { CumulativeProtocolDecoder c = new CumulativeProtocolDecoder() { @Override
    protected boolean doDecode(IoSession session, IoBuffer buffer, ProtocolDecoderOutput out)
    throws Exception {

    return true;
    }
    };
    return c;
    }
    }));
    acceptor.setHandler(new IoHandlerAdapter() { @Override
    public void sessionOpened(IoSession session) throws Exception {
    session.write("hello===============");
    session.write("hello===============>");
    }
    });
    try {
    acceptor.bind(new InetSocketAddress(60000));
    } catch (IOException e) {
    e.printStackTrace();
    }