YgslClient.java 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package com.mes.ygsl;
  2. import com.mes.netty.XDecoder;
  3. import com.mes.ui.MesClient;
  4. import com.mes.ui.YgslUtil;
  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. import java.util.concurrent.TimeUnit;
  16. public class YgslClient {
  17. public SocketChannel socketChannel;
  18. public static ChannelFuture future;
  19. public static String serverIp = "192.168.5.100"; // M6
  20. public void run(){
  21. //配置线程组
  22. EventLoopGroup group = new NioEventLoopGroup();
  23. //创建服务启动器
  24. Bootstrap bootstrap = new Bootstrap();
  25. //配置参数
  26. bootstrap.group(group)
  27. .channel(NioSocketChannel.class)
  28. .option(ChannelOption.TCP_NODELAY,true)
  29. .handler(new ChannelInitializer<SocketChannel>() {
  30. protected void initChannel(SocketChannel socketChannel) throws Exception {
  31. ByteBuf delimiter = Unpooled.copiedBuffer(new byte[]{0x00}); // 空位作为分隔符
  32. socketChannel.pipeline()
  33. .addLast(new DelimiterBasedFrameDecoder(1024, delimiter))
  34. .addLast("encoder", new StringEncoder(CharsetUtil.UTF_8))
  35. .addLast(new YgslClientHandler());
  36. }
  37. })
  38. .remoteAddress(serverIp,4545);
  39. //连接
  40. future = bootstrap.connect();
  41. System.out.println("Ygsl客户端正在连接服务端...");
  42. //客户端断线重连逻辑
  43. future.addListener((ChannelFutureListener) future1 -> {
  44. if (future1.isSuccess()) {
  45. //tcp连接成功
  46. MesClient.ygsl_tcp_connect_flag = true;
  47. //设置TCP请求状态
  48. MesClient.ygsl_connect_request_flag = false;
  49. System.out.println("连接Ygsl服务端成功");
  50. YgslUtil.comStart(MesClient.ygslClient);
  51. } else {
  52. //tcp连接失败
  53. MesClient.ygslClient = null;
  54. MesClient.ygsl_tcp_connect_flag = false;
  55. MesClient.ygsl_connect_request_flag = true;
  56. System.out.println("连接Ygsl失败,进行断线重连");
  57. // 延迟重连
  58. new Thread(() -> {
  59. try {
  60. Thread.sleep(100); // 延迟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. }