public class NettyClient {
private static final int MAX_RETRY = 5;
private static final int READ_TIMEOUT_SECONDS = 180;
public static void main(String[] args) {
String host = "localhost";
int port = 9090;
NioEventLoopGroup group = new NioEventLoopGroup();
int retry = 0;
while (retry < MAX_RETRY) {
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new IdleStateHandler(0, 0, READ_TIMEOUT_SECONDS, TimeUnit.SECONDS));
ch.pipeline().addLast(new ClientHandler());
}
});
ChannelFuture future = bootstrap.connect(host, port).sync();
log.info("客户端连接到" + host + ":" + port);
String message = "Hello, server!";
ByteBuf buffer = future.channel().alloc().buffer(message.length());
buffer.writeBytes(message.getBytes());
future.channel().writeAndFlush(buffer);
log.info("Message sent to server: " + message);
future.channel().closeFuture().sync();
} catch (Exception e) {
System.err.println("Failed to connect to " + host + ":" + port);
retry++;
try {
// Wait for 10 seconds before reconnecting
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException interruptedException) {
Thread.currentThread().interrupt();
}
}
}
log.info("已达到最大重试次数,请退出。");
group.shutdownGracefully();
}
private static class ClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf buf = (ByteBuf) msg;
String message = buf.toString(io.netty.util.CharsetUtil.UTF_8);
log.info("从服务器接收到消息: " + message);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleStateEvent.READER_IDLE_STATE_EVENT.state()) {
System.err.println("未收到的数据 " + READ_TIMEOUT_SECONDS + " 秒,关闭频道。");
ctx.close();
}
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.err.println("Connection lost, retrying to connect...");
ctx.channel().eventLoop().schedule(new Runnable() {
@Override
public void run() {
NettyClient.main(new String[0]);
}
}, 10, TimeUnit.SECONDS);
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
}
断线重连功能的Netty客户端程序示例。它将不断地尝试重新连接到服务器,如果连接被意外中断,将自动重新连接。
最新推荐文章于 2023-03-21 14:34:22 发布