【问题标题】:Close client connection in Netty在 Netty 中关闭客户端连接
【发布时间】:2015-09-20 21:57:49
【问题描述】:

我有简单的 Netty 客户端/服务器应用程序。在服务器端,我检查客户端是否从正确的主机连接,如果不正确,请关闭客户端的连接。在服务器端我使用这个代码:

@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        String remoteAddress = ctx.channel().remoteAddress().toString();
        if(!"/127.0.0.1:42477".equals(remoteAddress)) {
            ctx.writeAndFlush("Not correct remote address! Connection closed");
            ctx.close();
        }
        System.out.println(remoteAddress);
    }

在客户端这个:

@Override
    protected void channelRead0(ChannelHandlerContext ctx, String data) throws Exception {
        try {
            System.err.println(data);
        } finally {
            ReferenceCountUtil.retain(data);
        }       
    }

但我无法在 ctx.writeAndFlush() 中从服务器端获取消息,并且客户端关闭异常:

java.io.IOException: Соединение сброшено другой стороной(TRANSLATION: Connection reset from the other side)
    at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
    at sun.nio.ch.IOUtil.read(IOUtil.java:192)
    at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:379)
    at io.netty.buffer.UnpooledUnsafeDirectByteBuf.setBytes(UnpooledUnsafeDirectByteBuf.java:447)
    at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:881)
    at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:242)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:119)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:111)
    at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137)
    at java.lang.Thread.run(Thread.java:745)

如何以正确的方式关闭客户端连接?我是netty的新手

【问题讨论】:

    标签: java sockets netty


    【解决方案1】:

    ctx.writeAndFlush 是异步的,因此可能会在数据实际写入通道之前返回。但是,它返回一个ChannelFuture,它允许您添加一个侦听器,该侦听器将在操作完成时收到通知。要确保只有在数据写入后才关闭通道,您可以执行以下操作:

    ctx.writeAndFlush("Not correct remote address! Connection closed")
            .addListener(ChannelFutureListener.CLOSE);
    

    【讨论】:

    • 现在我只得到 java.nio.channels.ClosedChannelException 并且客户端连接关闭。但在客户端我无法从 ctx 获取消息
    • 哦,它正在工作)))我必须在我的警告字符串的末尾添加 \n。 tnx 为您提供帮助
    猜你喜欢
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    相关资源
    最近更新 更多