关闭Netty中的客户端连接

4

我有一个简单的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的新手。

1个回答

14

ctx.writeAndFlush 是异步的,因此可能在数据实际写入通道之前就返回了。但它会返回一个 ChannelFuture,让您可以添加一个监听器,在操作完成时得到通知。为确保通道关闭只发生在数据被写入后,您可以执行以下操作:

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

现在我只收到了java.nio.channels.ClosedChannelException和客户端连接关闭的消息。但是在客户端,我无法从ctx中获取消息。 - Jack Daniel
1
哦,它正在工作))) 我必须在我的警告字符串末尾添加 \n。谢谢你的帮助。 - Jack Daniel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接