Netty:处理exceptionCaught中剩余的入站数据

时间:2014-06-11 16:47:51

标签: exception netty

我需要构建一个非常简单的netty TCP服务器来处理从客户端发送的数据。服务器需要发回结果,但客户端不需要接收结果。因此,它可能会抛出在客户端关闭连接后发送结果导致的异常。通道似乎停滞不前,但我需要服务器做的是继续完成所有数据读取和放大处理

public class TCPServerHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = (ByteBuf) msg;
        String str = new String();
        String retstr;
        try {
            while (in.isReadable()) {
                char c = (char) in.readByte();
                if (c != '\n' && c != '\r' && c != SEP_BYTE) {
                    str += c;
                }
            }
            retstr = dosomething(str);
            ByteBuf ok = Unpooled.copiedBuffer(retstr, CharsetUtil.UTF_8);
            ctx.writeAndFlush(ok);//May trigger exceptionCaught when flushing
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        System.out.println("ExceptionCaught: sending channel closed by client");
        //cause.printStackTrace();
        //ctx.read();//not working
        //ctx.close();
    }

}

那我怎么能让netty继续" channelRead"异常捕获时缓冲区中已有的所有消息?

0 个答案:

没有答案