| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178 |
- package com.mes.netty;
- import io.netty.bootstrap.Bootstrap;
- import io.netty.channel.*;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioSocketChannel;
- import io.netty.handler.codec.string.StringEncoder;
- import java.util.concurrent.TimeUnit;
- import com.mes.ui.MesClient;
- public class NettyClient {
- public SocketChannel socketChannel;
- public ChannelFuture future;
- private static EventLoopGroup group;
- private static Bootstrap bootstrap;
- private volatile boolean connecting = false;
- private void ensureBootstrap() {
- if (group != null && !group.isShutdown()) {
- return;
- }
- group = new NioEventLoopGroup();
- bootstrap = new Bootstrap();
- bootstrap.group(group)
- .channel(NioSocketChannel.class)
- .option(ChannelOption.TCP_NODELAY, true)
- .option(ChannelOption.SO_KEEPALIVE, true)
- .handler(new ChannelInitializer<SocketChannel>() {
- @Override
- protected void initChannel(SocketChannel ch) {
- ch.pipeline()
- .addLast(new XDecoder())
- .addLast(new StringEncoder())
- .addLast(new NettyClientHandler());
- }
- })
- .remoteAddress(MesClient.mes_server_ip, MesClient.mes_tcp_port);
- }
- public void resetConnection() {
- connecting = false;
- future = null;
- socketChannel = null;
- }
- public boolean isChannelActive() {
- return future != null && future.channel() != null && future.channel().isActive();
- }
- public void run(Object msg) {
- if (isChannelActive()) {
- future.channel().writeAndFlush(msg);
- return;
- }
- if (connecting) {
- if (group != null && !group.isShutdown()) {
- group.schedule(() -> run(msg), 300, TimeUnit.MILLISECONDS);
- }
- return;
- }
- connecting = true;
- ensureBootstrap();
- System.out.println("客户端正在连接服务端...");
- future = bootstrap.connect();
- future.addListener((ChannelFutureListener) future1 -> {
- connecting = false;
- if (future1.isSuccess()) {
- MesClient.tcp_connect_flag = true;
- MesClient.connect_request_flag = false;
- System.out.println("连接Netty服务端成功");
- future1.channel().writeAndFlush(msg);
- } else {
- MesClient.tcp_connect_flag = false;
- MesClient.connect_request_flag = true;
- System.out.println("连接失败,进行断线重连");
- if (future1.channel() != null) {
- future1.channel().eventLoop().schedule(() -> run(msg), 10, TimeUnit.SECONDS);
- } else if (group != null) {
- group.schedule(() -> run(msg), 10, TimeUnit.SECONDS);
- }
- }
- MesClient.setTcpStatus();
- });
- socketChannel = (SocketChannel) future.channel();
- }
- }
|