Closing a client connection in Netty

I have a simple Netty client / network application. on the server side. I am checking if the client is connected to the correct host or not and if it is not correct then close the client connection. on the server side I am using this code:

@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);
    }

      

and on the client side this is:

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

      

but i cant get the server side message in ctx.writeAndFlush () and client side shutdown with exception:

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)

      

How can I close the client connection exactly? I am new to netty

+3


source to share


1 answer


ctx.writeAndFlush

is asynchronous and therefore can return before the data is actually written to the pipe. However, it does return ChannelFuture

, which allows you to add a listener that will be notified when the operation is complete. To ensure that the channel is closed only after the data has been written, you can do the following:



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

      

+7


source







All Articles