YgslClient2.java 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package com.mes.ygsl;
  2. import com.mes.ui.MesClient;
  3. import com.mes.ui.YgslUtil;
  4. import com.mes.ui.YgslUtil2;
  5. import io.netty.bootstrap.Bootstrap;
  6. import io.netty.buffer.ByteBuf;
  7. import io.netty.buffer.Unpooled;
  8. import io.netty.channel.*;
  9. import io.netty.channel.nio.NioEventLoopGroup;
  10. import io.netty.channel.socket.SocketChannel;
  11. import io.netty.channel.socket.nio.NioSocketChannel;
  12. import io.netty.handler.codec.DelimiterBasedFrameDecoder;
  13. import io.netty.handler.codec.string.StringEncoder;
  14. import io.netty.util.CharsetUtil;
  15. public class YgslClient2 {
  16. public SocketChannel socketChannel;
  17. public static ChannelFuture future;
  18. public static String serverIp = "192.168.5.101"; // M8
  19. public void run(){
  20. //配置线程组
  21. EventLoopGroup group = new NioEventLoopGroup();
  22. //创建服务启动器
  23. Bootstrap bootstrap = new Bootstrap();
  24. //配置参数
  25. bootstrap.group(group)
  26. .channel(NioSocketChannel.class)
  27. .option(ChannelOption.TCP_NODELAY,true)
  28. .handler(new ChannelInitializer<SocketChannel>() {
  29. protected void initChannel(SocketChannel socketChannel) throws Exception {
  30. ByteBuf delimiter = Unpooled.copiedBuffer(new byte[]{0x00}); // 空位作为分隔符
  31. socketChannel.pipeline()
  32. .addLast(new DelimiterBasedFrameDecoder(1024, delimiter))
  33. .addLast("encoder", new StringEncoder(CharsetUtil.UTF_8))
  34. .addLast(new YgslClientHandler2());
  35. }
  36. })
  37. .remoteAddress(serverIp,4545);
  38. //连接
  39. future = bootstrap.connect();
  40. System.out.println("Ygsl2客户端正在连接服务端"+serverIp+"...");
  41. //客户端断线重连逻辑
  42. future.addListener((ChannelFutureListener) future1 -> {
  43. if (future1.isSuccess()) {
  44. //tcp连接成功
  45. MesClient.ygsl_tcp_connect_flag2 = true;
  46. //设置TCP请求状态
  47. MesClient.ygsl_connect_request_flag2 = false;
  48. System.out.println("连接Ygsl2服务端成功");
  49. YgslUtil2.comStart(MesClient.ygslClient2);
  50. } else {
  51. //tcp连接失败
  52. MesClient.ygsl_tcp_connect_flag2 = false;
  53. MesClient.ygsl_connect_request_flag2 = true;
  54. System.out.println("连接Ygsl2失败,进行断线重连");
  55. // future1.channel().eventLoop().schedule(() -> run(), 1, TimeUnit.SECONDS);
  56. // 延迟重连
  57. new Thread(() -> {
  58. try {
  59. Thread.sleep(100); // 延迟0.5秒
  60. MesClient.initYgslTcpConnection();
  61. } catch (InterruptedException e) {
  62. Thread.currentThread().interrupt();
  63. }
  64. }).start();
  65. }
  66. });
  67. socketChannel = (SocketChannel) future.channel();
  68. }
  69. }