NettyClient.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package com.mes.netty;
  2. import com.mes.util.Config;
  3. import io.netty.bootstrap.Bootstrap;
  4. import io.netty.channel.*;
  5. import io.netty.channel.nio.NioEventLoopGroup;
  6. import io.netty.channel.socket.SocketChannel;
  7. import io.netty.channel.socket.nio.NioSocketChannel;
  8. import io.netty.handler.codec.string.StringEncoder;
  9. import java.util.concurrent.TimeUnit;
  10. import com.mes.ui.MesClient;
  11. import org.slf4j.Logger;
  12. import org.slf4j.LoggerFactory;
  13. public class NettyClient {
  14. public static final Logger log = LoggerFactory.getLogger(NettyClientHandler.class);
  15. public SocketChannel socketChannel;
  16. public static ChannelFuture future;
  17. public void run(Object msg){
  18. //配置线程组
  19. EventLoopGroup group = new NioEventLoopGroup();
  20. //创建服务启动器
  21. Bootstrap bootstrap = new Bootstrap();
  22. //配置参数
  23. bootstrap.group(group)
  24. .channel(NioSocketChannel.class)
  25. .option(ChannelOption.TCP_NODELAY,true)
  26. .handler(new ChannelInitializer<SocketChannel>() {
  27. protected void initChannel(SocketChannel socketChannel) throws Exception {
  28. socketChannel.pipeline()
  29. .addLast(new XDecoder())
  30. .addLast(new StringEncoder())
  31. // .addLast(new StringDecoder())
  32. .addLast(new NettyClientHandler());
  33. }
  34. })
  35. .remoteAddress(Config.server_ip, Config.tcp_port);
  36. //连接
  37. future = bootstrap.connect();
  38. log.info("客户端正在连接服务端...");
  39. //客户端断线重连逻辑
  40. future.addListener((ChannelFutureListener) future1 -> {
  41. if (future1.isSuccess()) {
  42. MesClient.tcp_connect_flag = true; //tcp连接成功
  43. MesClient.allow_connect_again = true; // 当下一次连接断开时, 允许再次发送同步请求
  44. log.info("连接Netty服务端成功");
  45. future.channel().writeAndFlush(msg);
  46. } else {
  47. //tcp连接失败
  48. MesClient.tcp_connect_flag = false;
  49. log.info("连接失败,进行断线重连");
  50. future1.channel().eventLoop().schedule(() -> run(msg), 10, TimeUnit.SECONDS);
  51. }
  52. });
  53. socketChannel = (SocketChannel) future.channel();
  54. }
  55. }