要设置 Netty TCP 连接的超时时间,可以使用'IdleStateHandler'来实现。以下是一个示例代码,设置了 5 秒的读取超时时间。

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class TcpClient {
    private final String host;
    private final int port;

    public TcpClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new IdleStateHandler(0, 0, 5, TimeUnit.SECONDS));
                            // 添加其他的 handler
                            // ch.pipeline().addLast(...);
                        }
                    });

            ChannelFuture f = b.connect(host, port).sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        String host = "localhost";
        int port = 8080;
        new TcpClient(host, port).run();
    }
}

在上述代码中,通过'IdleStateHandler'设置了读取超时时间为 5 秒。如果在 5 秒内没有收到任何数据,连接将会被断开。可以根据需要调整'IdleStateHandler'的参数来设置不同的超时时间。

Java Netty TCP 连接超时设置:5 秒无响应断开连接

原文地址: https://www.cveoy.top/t/topic/eEGl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录