客戶端代碼
public class NettyClient {
static NioEventLoopGroup group = new NioEventLoopGroup(8);
static Bootstrap bootstrap = new Bootstrap();
static volatile Channel channel = null;
public static void main(String[] args) throws InterruptedException {
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline()
.addLast("ping", new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS))
.addLast(new ObjectEncoder())
.addLast(new ObjectDecoder((s)->{
return String.class;
})).addLast(new ChannelInboundHandlerAdapter(){
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("斷線了");
ctx.channel().eventLoop().schedule(()->{
System.out.println("斷線重連");
connect();
// ctx.connect(new InetSocketAddress("127.0.0.1", 8666));
// ctx.channel().close();
}, 1L, TimeUnit.SECONDS);
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent){
// if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE){
// System.out.println("度空閒");
// ctx.writeAndFlush("sasa");
// }
}else{
super.userEventTriggered(ctx, evt);
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("連接 == " + ctx);
channel = ctx.channel();
super.channelActive(ctx);
}
});
}
});
connect();
Thread thread = new Thread(){
@Override
public void run() {
int num = 100;
while (num -- > 0){
// try {
// Thread.sleep(1000L);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
try {
if (channel != null && channel.isActive()){
channel.writeAndFlush("測試" + UUID.randomUUID().toString() + "#@");
}else if(channel == null || !channel.isActive()){
System.out.println("不可寫 稍等 ++++");
Thread.sleep(1000L);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
};
thread.setDaemon(true);
thread.start();
}
private static void connect(){
ChannelFuture future = bootstrap.connect("127.0.0.1", 8666)
.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture ch) throws Exception {
if (!ch.isSuccess()) {
ch.channel().close();
final EventLoop loop = ch.channel().eventLoop();
loop.schedule(new Runnable() {
@Override
public void run() {
System.err.println("服務端鏈接不上,開始重連操作...");
connect();
// ch.(new InetSocketAddress("127.0.0.1", 8666));
// ch.channel().close();
}
}, 1L, TimeUnit.SECONDS);
} else {
ch.channel().writeAndFlush("你好");
System.err.println("服務端鏈接成功...");
}
}
});
}
}
服務端代碼:
public class NettyServer { public static final int port = 8666; public static void main(String[] args) { NioEventLoopGroup boss = new NioEventLoopGroup(8); NioEventLoopGroup work = new NioEventLoopGroup(16); try { ServerBootstrap server = new ServerBootstrap().group(boss, work); server.channel(NioServerSocketChannel.class) .handler(new ChannelInitializer<ServerSocketChannel>() { @Override protected void initChannel(ServerSocketChannel ch) throws Exception { System.out.println("服務啓動中"); } }) .childOption(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.SO_BACKLOG, 1024) .childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.TCP_NODELAY, true) .childHandler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) throws Exception { ch.pipeline() .addLast(new IdleStateHandler(true, 5, 3, 0, TimeUnit.SECONDS)) .addLast(new ObjectEncoder()) .addLast(new ObjectDecoder((s)->{ return String.class; })) .addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { System.out.println(msg); }finally { ReferenceCountUtil.release(msg); } } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { System.out.println(((IdleStateEvent) evt).state() + ">>>" + ctx.channel()); } super.userEventTriggered(ctx, evt); } }); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { System.out.println("有新連接了 ++++ "); super.handlerAdded(ctx); } }); ChannelFuture future = server.bind(port).sync(); future.channel().closeFuture().sync(); future.addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { if (future.isSuccess()) { System.out.println("服務啓動成功"); } else { System.out.println("服務啓動失敗"); } } }); } catch (InterruptedException e) { e.printStackTrace(); } finally { boss.shutdownGracefully(); work.shutdownGracefully(); } } }