Netty中的捕获异常和转移异常

时间:2018-10-12 11:27:45

标签: java exception-handling netty

在客户端从服务器接收消息或向服务器发送消息或从服务器发送消息后,我试图识别任何异常。并且,如果发生任何异常,我想关闭连接并说“由于'this'异常而关闭了连接”等。

连接

public static boolean connect(Host host, String message, int mode) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap clientBootstrap = new Bootstrap();

            clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100);

            clientBootstrap.group(group);
            clientBootstrap.channel(NioSocketChannel.class);
            clientBootstrap.remoteAddress(new InetSocketAddress(host.getIp(), host.getPort()));

            clientBootstrap.handler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel socketChannel) {

                    //TODO, TIMEOUT BILGISI ILE DOLDUR BURAYI
                    //socketChannel.pipeline().addLast(new ReadTimeoutHandler(1));
                    //socketChannel.pipeline().addLast("idleStateHandler", new IdleStateHandler(2, 2, 4));

                    socketChannel.pipeline().addLast(new FalconClientHandler(host, message, mode));
                }
            });

            ChannelFuture channelFuture = clientBootstrap.connect().sync();

            //TODO I NEED TO CATCH IT SOMEWHERE IN HERE
            channelFuture.channel().closeFuture().sync();
            return true;
        } catch (Exception e) {
            System.err.println("Connection timed out --> " + e);
            host.setActive(false); //connection kurulamadı demektir. Bir sonraki mesaj geldiğinde bu hostun açılıp açılmadığı denenecek.
            return false;
        } finally {
            group.shutdownGracefully().sync();
            if (mode == 0) { //arka planda sunucu hep ayakta olmalı. Mode 0 da asla bağlantı kesilmemeli. Kesiliyorsa host kapanmıştır.
                host.setActive(false);
                return false;
            }
        }
    }

捕获异常

@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {
        cause.printStackTrace();
        //CLOSE CONNECTION AND I HAVE TO PASS THE INFORMATION WHY CONNECTION CLOSED
        ctx.close();
    }

读取功能

@Override
    public void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf in) {
        InetSocketAddress socketAddress = (InetSocketAddress) channelHandlerContext.channel().remoteAddress();
        InetAddress inetaddress = socketAddress.getAddress();
        String ipAddress = inetaddress.getHostAddress(); // IP address of client

        TCPHandshakeMessage tcpMessage;
        byte[] signal;
        String input = in.toString(CharsetUtil.US_ASCII);

        /*
         * mode 0 -> Amaç sunucuların ayakta olup olmadığını anlamak
         * mode 1 -> Amaç sunuculara mesaj göndermek
         * */
        if(this.mode == 1){  //MODE 1 BAŞLANGICI
            //I WRITE THIS ON PURPOSE
            double x = 12 / 0;
            System.err.println("MESSAGE SENT TO " + message + " IP : " + ipAddress);
            this.host.setActive(true);
            //TODO TCP MESSAGE SINIFINI KULLAN
            signal = message.getBytes();
            sendMessage(channelHandlerContext, signal);
            /*try {

            }catch (Exception e){
                System.out.println("An Error Occured " + e);
            }finally {
                channelHandlerContext.channel().close();
            }*/
        }
}

我应该在CONNECTION区域中使用channelFuture.addListener()吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

如果是HTTP 1.1请求,则可以按以下方式处理异常:

@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR))
                .addListener(ChannelFutureListener.CLOSE);
        LOG.error("Error occured", cause);
    }

ChannelFutureListener.CLOSE侦听器将在writeAndFlush成功后关闭连接