| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- package com.mes.ygsl;
- import com.mes.netty.XDecoder;
- import com.mes.ui.MesClient;
- import com.mes.ui.YgslUtil;
- 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;
- import java.util.concurrent.TimeUnit;
- public class YgslClient {
- public SocketChannel socketChannel;
- public static ChannelFuture future;
- public static String serverIp = "192.168.5.100"; // M6
- 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失败,进行断线重连");
- // 延迟重连
- new Thread(() -> {
- try {
- Thread.sleep(100); // 延迟0.5秒
- MesClient.initYgslTcpConnection();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }).start();
- }
- });
- socketChannel = (SocketChannel) future.channel();
- }
- }
|