简体   繁体   English

如何在没有工作组终止的情况下正确关闭 netty 通道

[英]How to correcly close netty channel without workgroup termination

I have following binding to handle UDP packets我有以下绑定来处理 UDP 数据包

 private void doStartServer() {
        final UDPPacketHandler udpPacketHandler = new UDPPacketHandler(messageDecodeHandler);
        workerGroup = new NioEventLoopGroup(threadPoolSize);

        try {
            final Bootstrap bootstrap = new Bootstrap();
            bootstrap
                .group(workerGroup)
                .handler(new LoggingHandler(nettyLevel))
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(udpPacketHandler);

            bootstrap
                .bind(serverIp, serverPort)
                .sync()
                .channel()
                .closeFuture()
                .await();
        } finally {
            stop();
        }
    }

and handler和处理程序

@ChannelHandler.Sharable    << note this
@Slf4j
@AllArgsConstructor
public class UDPPacketHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private final MessageP54Handler messageP54Handler;

    @Override
    public void channelReadComplete(final ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
        log.error("Exception in UDP handler", cause);
        ctx.close();
    }
}

At some point I get this exception java.net.SocketException: Network dropped connection on reset: no further information which is handled in exceptionCaught .在某些时候,我得到了这个异常java.net.SocketException: Network dropped connection on reset: no further information which is processed in exceptionCaught This triggers ChannelHandlerContext to close.这会触发ChannelHandlerContext关闭。 And at this point whole my server stops (executing on finnaly block from first snippet)在这一点上,我的整个服务器都停止了(在第一个片段的finnaly块上执行)

How to correctly handle exception so that I can handle new connections even after such exception occurs?如何正确处理异常,以便即使在发生此类异常后也可以处理新连接?

you shouldn't close the ChannelHandlerContext on an IOException when using a DatagramChannel .使用DatagramChannel时,不应在IOException上关闭ChannelHandlerContext As DatagramChannel is "connection-less" the exception is specific to one "receive" or one "send" operation.由于DatagramChannel是“无连接”的,因此异常特定于一个“接收”或一个“发送”操作。 So just log it (or whatever you want to do) and move on.所以只需记录它(或任何你想做的事情)并继续前进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM