| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- package com.mes.ygsl;
- import com.mes.ui.MesClient;
- import io.netty.bootstrap.Bootstrap;
- import io.netty.buffer.ByteBuf;
- import io.netty.buffer.Unpooled;
- 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.DelimiterBasedFrameDecoder;
- import io.netty.handler.codec.string.StringEncoder;
- import io.netty.util.CharsetUtil;
- public class YgslClient {
- public SocketChannel socketChannel;
- public static ChannelFuture future;
- public static String serverIp = "192.168.1.100"; // M5
- public void run(){
- //配置线程组
- EventLoopGroup group = new NioEventLoopGroup();
- //创建服务启动器
- Bootstrap bootstrap = new Bootstrap();
- //配置参数
- bootstrap.group(group)
- .channel(NioSocketChannel.class)
- .option(ChannelOption.TCP_NODELAY,true)
- .handler(new ChannelInitializer<SocketChannel>() {
- protected void initChannel(SocketChannel socketChannel) throws Exception {
- ByteBuf delimiter = Unpooled.copiedBuffer(new byte[]{0x00}); // 空位作为分隔符
- socketChannel.pipeline()
- .addLast(new DelimiterBasedFrameDecoder(1024, delimiter))
- .addLast("encoder", new StringEncoder(CharsetUtil.UTF_8))
- .addLast(new YgslClientHandler());
- }
- })
- .remoteAddress(serverIp,4545);
- //连接
- future = bootstrap.connect();
- System.out.println("Ygsl客户端正在连接服务端...");
- //客户端断线重连逻辑
- future.addListener((ChannelFutureListener) future1 -> {
- if (future1.isSuccess()) {
- //tcp连接成功
- MesClient.ygsl_tcp_connect_flag = true;
- //设置TCP请求状态
- MesClient.ygsl_connect_request_flag = false;
- System.out.println("连接Ygsl服务端成功");
- YgslUtil.comStart(MesClient.ygslClient);
- } else {
- //tcp连接失败
- MesClient.ygslClient = null;
- MesClient.ygsl_tcp_connect_flag = false;
- MesClient.ygsl_connect_request_flag = true;
- // System.out.println("连接Ygsl失败,进行断线重连");
- Throwable cause = future1.cause(); // 获取失败原因
- // System.out.println("连接Ygsl失败,原因:" + cause.getMessage());
- cause.printStackTrace(); // 打印详细异常堆栈
- // 延迟重连
- new Thread(() -> {
- try {
- Thread.sleep(1000); // 延迟0.5秒
- MesClient.initYgslTcpConnection();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }).start();
- }
- });
- socketChannel = (SocketChannel) future.channel();
- }
- }
|