通道关闭时,Netty Server无法发送所有数据

时间:2019-03-07 17:09:18

标签: netty

我是netty的新手,不了解为什么服务器响应在我的服务器中部分丢失。我已经阅读了几个问题,但无法解决问题。

我正在使用netty 4.0.46版本。 发送完所有响应数据后,服务器必须关闭连接。 我正在使用SimpleChannelInboundHandler,并尝试在发送响应后尝试使用ChannelFutureListener关闭通道。

public class AlbaranXMLServerHandler extends SimpleChannelInboundHandler<String> {
...
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String host = ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress();
        int port = ((InetSocketAddress)ctx.channel().remoteAddress()).getPort();
        logger.debug(String.format("Nueva conexión. host:%s port:%d", host, port));
    }

@Override
public void channelRead0(ChannelHandlerContext ctx, String request)
        throws Exception {

    logger.info("Request received: " + request);
    .......

    logger.debug("XML Response: " + response);  

    ChannelFuture future = ctx.writeAndFlush(response);
    future.addListener(ChannelFutureListener.CLOSE);
    .......
}

当响应数据(XML字符串)很少时,就没有问题,并且客户端将接收完整的XML。但是,当涉及到大型XML文件时,传输会中断,显然是在侦听器关闭通道时。

服务器日志调试始终显示完整的XML Ok。

关于Netty写入/关闭频道的方式,我是否缺少某些东西?

ChannelInitializer

public class AlbaranXMLServerInitializer extends ChannelInitializer<SocketChannel> {
......
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // Add the text line codec combination first,
        pipeline.addLast("framer", new FixedLengthFrameDecoder(AlbaranXMLServerHandler.TRAMA_PETICION_LONGITUD));
        // the encoder and decoder are static as these are sharable
        pipeline.addLast("decoder", DECODER);
        pipeline.addLast("encoder", ENCODER);

        // and then business logic.
        pipeline.addLast("handler", new AlbaranXMLServerHandler(rutaAlbaranes, autenticacionRFCService, albaranXMLRFCService, grupoSociedadesRFCService));
    }
}

服务器

            @Service 
public class AlbaranXMLServer extends SocketServerBase {
    logger.info("Inicializando el servicio " + this.getClass().getSimpleName() + " ...");

            bossGroup = new NioEventLoopGroup();
            workerGroup = new NioEventLoopGroup();

            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(this.getChannelInitializer());

                Channel channel = b.bind(port).sync().channel();
                logger.info("Finalizada la inicialización del servicio " + this.getClass().getSimpleName());

            } catch (Exception e) {
                logger.warn("Error al inicializar el servicio " + this.getClass().getSimpleName(), e);
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }

0 个答案:

没有答案