| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- package com.mes.ygsl;
- import com.mes.ui.MesClient;
- import com.mes.ui.YgslUtil;
- import com.mes.ui.YgslUtil2;
- 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 YgslClient2 {
- public SocketChannel socketChannel;
- public static ChannelFuture future;
- public static String serverIp = "192.168.5.101"; // M8
- 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 YgslClientHandler2());
- }
- })
- .remoteAddress(serverIp,4545);
- //连接
- future = bootstrap.connect();
- System.out.println("Ygsl2客户端正在连接服务端"+serverIp+"...");
- //客户端断线重连逻辑
- future.addListener((ChannelFutureListener) future1 -> {
- if (future1.isSuccess()) {
- //tcp连接成功
- MesClient.ygsl_tcp_connect_flag2 = true;
- //设置TCP请求状态
- MesClient.ygsl_connect_request_flag2 = false;
- System.out.println("连接Ygsl2服务端成功");
- YgslUtil2.comStart(MesClient.ygslClient2);
- } else {
- //tcp连接失败
- MesClient.ygsl_tcp_connect_flag2 = false;
- MesClient.ygsl_connect_request_flag2 = true;
- System.out.println("连接Ygsl2失败,进行断线重连");
- // future1.channel().eventLoop().schedule(() -> run(), 1, TimeUnit.SECONDS);
- // 延迟重连
- new Thread(() -> {
- try {
- Thread.sleep(100); // 延迟0.5秒
- MesClient.initYgslTcpConnection();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }).start();
- }
- });
- socketChannel = (SocketChannel) future.channel();
- }
- }
|