package com.casic.missiles.client; import com.casic.missiles.modular.system.util.RSAUtil; import io.netty.buffer.Unpooled; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.nio.charset.StandardCharsets; import java.util.Date; @Slf4j @Component public class NettyClientSendMsg { // private static final String host = "172.17.240.116"; private static String host ; private static String port; @Value("${casic.brAddress}") public void setHost(String brAddress) { NettyClientSendMsg.host = brAddress.split(":")[0]; } @Value("${casic.brAddress}") public void setPort(String brAddress) { NettyClientSendMsg.port =brAddress.split(":")[1]; } public static void main(String[] args) { // 初始化Netty连接 String userId = "1"; if (null == ChannelUtil.getChannelByName(userId) || (!ChannelUtil.getChannelByName(userId).isActive())) { ChannelUtil.removeChannelByName(userId); new NettyClient().initNetty(userId, host, Integer.valueOf(port)); } ChannelUtil.getChannelByName(userId).writeAndFlush("22\n"); // 根据用户id发送消息到客户端 // PosttingObject posttingObject = NettyClient.concurrentHashMap.get(userId); try{ // 发送消息 // NettyClient nettyClient = posttingObject.getNettyClient(); // nettyClient.clientHandler.sendMessage(Unpooled.copiedBuffer("11".getBytes(StandardCharsets.UTF_8))); // nettyClient.clientHandler.sendMessage("22\n"); // nettyClient.clientHandler.sendMessage("33\n"); } finally { // 优雅关闭连接 // posttingObject.getNioEventLoopGroup().shutdownGracefully(); } sendData("1", "257"); } private volatile static long count=0; public static void sendData(String userId, String msg) { System.out.println(new Date() + ":" + userId.concat(" send ------->").concat(msg)); if (null == ChannelUtil.getChannelByName(userId) || (!ChannelUtil.getChannelByName(userId).isActive())) { ChannelUtil.removeChannelByName(userId); count++; if(count%60*3==0) { System.out.println("开始链接------------------------>"); new NettyClient().initNetty(userId, host, Integer.valueOf(port)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } if (null != ChannelUtil.getChannelByName(userId) && ChannelUtil.getChannelByName(userId).isActive()) { System.out.println("开始发送------------------------>"); count=0; //对数据进行协议格式和加密处理 String msgStr = MsgUtil.getMsg(msg, "1", ""); String encodeMsgStr = RSAUtil.getMsg(msgStr); ChannelUtil.getChannelByName(userId).writeAndFlush(Unpooled.copiedBuffer(encodeMsgStr.getBytes(StandardCharsets.UTF_8))); System.out.println("已发送原始数据-->"+msgStr); // System.out.println("已发送加密数据-->"+encodeMsgStr); } } }