我正在使用netty开发代理服务器,我的代理ProxyBackendHandler类如下。在channelRead方法上,我需要获取msg数据并将其作为TextWebSocketFrame写入客户端。为此,我使用了一个StringBuilder和一个while循环来迭代ByteBuf。任何人都可以建议我一种更好的方法来执行此操作,因为在加载大量数据时,上述代码似乎具有较高的性能开销。

public class ProxyBackendHandler extends ChannelInboundHandlerAdapter {

    private final Channel inboundChannel;
    StringBuilder sReplyBuffer;

    public ProxyBackendHandler(Channel inboundChannel) {
        this.inboundChannel = inboundChannel;
        sReplyBuffer = new StringBuilder(4000);
    }

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) {

        // Please suggest a efficient implementation for read msg and pass it to writeAndFlush.
        ByteBuf in = (ByteBuf) msg;
        sReplyBuffer.setLength(0);

        try {
            while (in.isReadable()) {
                sReplyBuffer.append((char) in.readByte());
            }
        } finally {
            ((ByteBuf) msg).release();
        }

        inboundChannel.writeAndFlush(new TextWebSocketFrame (sReplyBuffer.toString())).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ctx.channel().read();
                    System.out.println("Sent To Client");
                } else {
                    future.channel().close();
                }
            }
        });
    }
}

最佳答案

也许是这样的:

public class ProxyBackendHandler extends ChannelInboundHandlerAdapter {

    private final Channel inboundChannel;

    public ProxyBackendHandler(Channel inboundChannel) {
        this.inboundChannel = inboundChannel;
    }

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) {
        inboundChannel.writeAndFlush(new TextWebSocketFrame((ByteBuf) msg)).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ctx.channel().read();
                    System.out.println("Sent To Client");
                } else {
                    future.channel().close();
                }
            }
        });
    }
}

关于java - Java Netty Server的高效channelRead,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33476329/

10-12 01:42