YgslClient.java 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package com.mes.ygsl;
  2. import com.mes.ui.MesClient;
  3. import io.netty.bootstrap.Bootstrap;
  4. import io.netty.buffer.ByteBuf;
  5. import io.netty.buffer.Unpooled;
  6. import io.netty.channel.*;
  7. import io.netty.channel.nio.NioEventLoopGroup;
  8. import io.netty.channel.socket.SocketChannel;
  9. import io.netty.channel.socket.nio.NioSocketChannel;
  10. import io.netty.handler.codec.DelimiterBasedFrameDecoder;
  11. import io.netty.handler.codec.string.StringEncoder;
  12. import io.netty.util.CharsetUtil;
  13. public class YgslClient {
  14. public SocketChannel socketChannel;
  15. public static ChannelFuture future;
  16. public static String serverIp = "192.168.1.100"; // M5
  17. public void run(){
  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. ByteBuf delimiter = Unpooled.copiedBuffer(new byte[]{0x00}); // 空位作为分隔符
  29. socketChannel.pipeline()
  30. .addLast(new DelimiterBasedFrameDecoder(1024, delimiter))
  31. .addLast("encoder", new StringEncoder(CharsetUtil.UTF_8))
  32. .addLast(new YgslClientHandler());
  33. }
  34. })
  35. .remoteAddress(serverIp,4545);
  36. //连接
  37. future = bootstrap.connect();
  38. System.out.println("Ygsl客户端正在连接服务端...");
  39. //客户端断线重连逻辑
  40. future.addListener((ChannelFutureListener) future1 -> {
  41. if (future1.isSuccess()) {
  42. //tcp连接成功
  43. MesClient.ygsl_tcp_connect_flag = true;
  44. //设置TCP请求状态
  45. MesClient.ygsl_connect_request_flag = false;
  46. System.out.println("连接Ygsl服务端成功");
  47. YgslUtil.comStart(MesClient.ygslClient);
  48. } else {
  49. //tcp连接失败
  50. MesClient.ygslClient = null;
  51. MesClient.ygsl_tcp_connect_flag = false;
  52. MesClient.ygsl_connect_request_flag = true;
  53. // System.out.println("连接Ygsl失败,进行断线重连");
  54. Throwable cause = future1.cause(); // 获取失败原因
  55. // System.out.println("连接Ygsl失败,原因:" + cause.getMessage());
  56. cause.printStackTrace(); // 打印详细异常堆栈
  57. // 延迟重连
  58. new Thread(() -> {
  59. try {
  60. Thread.sleep(1000); // 延迟0.5秒
  61. MesClient.initYgslTcpConnection();
  62. } catch (InterruptedException e) {
  63. Thread.currentThread().interrupt();
  64. }
  65. }).start();
  66. }
  67. });
  68. socketChannel = (SocketChannel) future.channel();
  69. }
  70. }