如何使用netty从服务器向客户端发送确认?

时间:2012-03-28 10:10:21

标签: java netty

任何人都可以解释如何使用 netty 从服务器向设备发送确认。

我使用以下代码:

public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
            throws Exception {

    String msg = null;
    String IMIE = null;
    String[] str = null;
    String ack = null;
    StringBuffer sbs = new StringBuffer();
    ChannelBuffer buf = (ChannelBuffer) e.getMessage();

    while(buf.readable()) {
        sbs.append((char) buf.readByte());          
    }

    msg = sbs.toString();
    System.out.println(msg);


    byte[] request = new byte[] { 0x01 };
    e.getChannel().write(request,e.getChannel().getRemoteAddress());
    System.out.flush(); 

并且收到错误

  

java.lang.IllegalArgumentException:不支持的消息类型:class [B

请帮助我。

1 个答案:

答案 0 :(得分:4)

您需要将字节数组包装到ChannelBuffer中,或添加一个为您执行此操作的编码器。所以最简单的解决方法是:

public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
        throws Exception {

    String msg = null;
    String IMIE = null;
    String[] str = null;
    String ack = null;
    ChannelBuffer buf = null;
    StringBuffer sbs = new StringBuffer();
    buf = (ChannelBuffer) e.getMessage();
    while(buf.readable()) {
        sbs.append((char) buf.readByte());
     }

    msg = sbs.toString();
    System.out.println(msg);


    byte[] request = new byte[] { 0x01 };
    e.getChannel().write(ChannelBuffers.wrappedBuffer(request));
    System.out.flush(); 
}