Commit 3fd11a1b authored by duanruiming's avatar duanruiming

[add] 添加tcp协议

parent e3c8255a
package net.wanji.utc.hisense; package net.wanji.utc.hisense;
import net.wanji.utc.hisense.netty.NettyClient; import net.wanji.utc.hisense.netty.TcpClient;
import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner; import org.springframework.boot.CommandLineRunner;
...@@ -23,6 +23,8 @@ public class HisenseApplication implements CommandLineRunner { ...@@ -23,6 +23,8 @@ public class HisenseApplication implements CommandLineRunner {
int localPort; int localPort;
@Value("${portParam.remotePort}") @Value("${portParam.remotePort}")
int remoteProt; int remoteProt;
@Value("${portParam.remoteIp}")
String remoteIp;
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(HisenseApplication.class, args); SpringApplication.run(HisenseApplication.class, args);
...@@ -30,6 +32,7 @@ public class HisenseApplication implements CommandLineRunner { ...@@ -30,6 +32,7 @@ public class HisenseApplication implements CommandLineRunner {
@Override @Override
public void run(String... args) throws Exception { public void run(String... args) throws Exception {
NettyClient.connection(localPort, remoteProt); //UdpClient.connection(localPort, remoteProt);
TcpClient.connection(remoteIp, remoteProt);
} }
} }
package net.wanji.utc.hisense.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import net.wanji.utc.hisense.netty.handler.TcpClientHandler;
import org.springframework.stereotype.Component;
/**
* @author duanruiming
* @date 2024/01/08 17:33
*/
@Slf4j
@Component
public class TcpClient {
public static void connection(String host, int port) throws Exception {
EventLoopGroup group = new NioEventLoopGroup(); // 创建线程组
try {
Bootstrap b = new Bootstrap(); // 创建客户端启动对象
b.group(group) // 设置线程组
.channel(NioSocketChannel.class) // 设置通道实现类
.handler(new ChannelInitializer<Channel>() { // 设置通道初始化对象
@Override
protected void initChannel(Channel ch) throws Exception {
//ch.pipeline().addLast(new XmlMessageDecoder()); // 添加自定义的解码器
//ch.pipeline().addLast(new XmlMessageEncoder()); // 添加自定义的编码器
ch.pipeline().addLast(new TcpClientHandler()); // 添加自定义的处理器
}
});
// 启动客户端,连接到服务器端,并同步,生成ChannelFuture对象
ChannelFuture f = b.connect(host, port).sync();
// 对关闭通道进行监听
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully(); // 关闭线程组
}
}
}
...@@ -13,7 +13,7 @@ import net.wanji.utc.hisense.cache.CrossInfoCache; ...@@ -13,7 +13,7 @@ import net.wanji.utc.hisense.cache.CrossInfoCache;
import net.wanji.utc.hisense.cache.netty.NettyMessageCache; import net.wanji.utc.hisense.cache.netty.NettyMessageCache;
import net.wanji.utc.hisense.netty.codec.MessageDecoder; import net.wanji.utc.hisense.netty.codec.MessageDecoder;
import net.wanji.utc.hisense.netty.codec.MessageEnCoder; import net.wanji.utc.hisense.netty.codec.MessageEnCoder;
import net.wanji.utc.hisense.netty.handler.NettyServerHandler; import net.wanji.utc.hisense.netty.handler.UdpClientHandler;
import net.wanji.utc.hisense.pojo.netty.MessageResultPojo; import net.wanji.utc.hisense.pojo.netty.MessageResultPojo;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
...@@ -29,7 +29,7 @@ import java.util.concurrent.TimeUnit; ...@@ -29,7 +29,7 @@ import java.util.concurrent.TimeUnit;
@Slf4j @Slf4j
@Component @Component
public class NettyClient { public class UdpClient {
private static ChannelFuture udpChannelFuture = null; private static ChannelFuture udpChannelFuture = null;
@Resource(name = "commonThreadPoolExecutor") @Resource(name = "commonThreadPoolExecutor")
private ThreadPoolTaskExecutor commonThreadPoolExecutor; private ThreadPoolTaskExecutor commonThreadPoolExecutor;
...@@ -51,7 +51,7 @@ public class NettyClient { ...@@ -51,7 +51,7 @@ public class NettyClient {
datagramChannel.pipeline() datagramChannel.pipeline()
.addLast("decoder", new MessageDecoder()) .addLast("decoder", new MessageDecoder())
.addLast("encoder", new MessageEnCoder()) .addLast("encoder", new MessageEnCoder())
.addLast(new NettyServerHandler()); .addLast(new UdpClientHandler());
} }
}); });
ChannelFuture channelFuture = bootstrap.bind().sync(); ChannelFuture channelFuture = bootstrap.bind().sync();
...@@ -61,7 +61,7 @@ public class NettyClient { ...@@ -61,7 +61,7 @@ public class NettyClient {
log.warn("udp服务关闭!"); log.warn("udp服务关闭!");
})); }));
log.info("udp服务正在运行,端口:{}", localPort); log.info("udp服务正在运行,端口:{}", localPort);
NettyClient.udpChannelFuture = channelFuture; UdpClient.udpChannelFuture = channelFuture;
} }
public static void sendMessage(String ip, Integer port, String msg) { public static void sendMessage(String ip, Integer port, String msg) {
......
package net.wanji.utc.hisense.netty.handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import lombok.extern.slf4j.Slf4j;
import net.wanji.common.framework.spring.ServiceBeanContext;
import net.wanji.databus.po.CrossInfoPO;
import net.wanji.utc.hisense.cache.CrossInfoCache;
import net.wanji.utc.hisense.cache.SignalDataCache;
import net.wanji.utc.hisense.cache.netty.NettyMessageCache;
import net.wanji.utc.hisense.common.enums.CommandResultSignEnum;
import net.wanji.utc.hisense.netty.commandsign.CommandResultSign;
import net.wanji.utc.hisense.netty.pojo.CommandPojo;
import net.wanji.utc.hisense.netty.response.CommandResponseFactory;
import net.wanji.utc.hisense.pojo.convert.RunningLightsStatusPojo;
import net.wanji.utc.hisense.pojo.netty.MessageResultPojo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;
/**
* @author duanruiming
* @date 2024/01/08 17:44
*/
@Slf4j
@Component
public class TcpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
/**
* 读取消息
*
* @param ctx
* @param packet
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
ByteBuf content = packet.content();
InetSocketAddress remote = packet.sender();
int i = content.readableBytes();
byte[] b = new byte[i];
content.readBytes(b);
String data = new String(b, StandardCharsets.UTF_8);
Object resultPojo = CommandResultSign.getHexSign(data);
log.error("当前收到海信数据转化实体: {}", resultPojo);
String className = CommandResultSignEnum.getResultPojo(resultPojo);
if (CommandResultSignEnum.GET_RUNNING_STATE_INFO.getClassName().equals(className)) {
// 直接set灯态缓存
RunningLightsStatusPojo pojo = (RunningLightsStatusPojo) resultPojo;
String signalCode = pojo.getCID();
CrossInfoPO crossInfoPO = CrossInfoCache.getCrossInfoBySignalCode(signalCode);
if (Objects.nonNull(crossInfoPO)) {
Map<String, RunningLightsStatusPojo> cache = SignalDataCache.runningStateInfoCacheUdp;
cache.put(crossInfoPO.getId(), pojo);
}
return;
}
CommandResponseFactory commandResponseFactory = ServiceBeanContext.getBean(className);
String key = StringUtils.join("/", remote.getHostString(), ":", remote.getPort(), "/", resultPojo.getClass().getSimpleName());
CommandPojo commandPojo = getCommandPojo(key, resultPojo);
Object hexResult = commandResponseFactory.getCommandResponse(commandPojo);
if (Objects.nonNull(hexResult)) {
setResultData(key, hexResult);
}
}
private void setResultData(String key, Object hexResult) {
MessageResultPojo resultPojo = NettyMessageCache.NETTY_RESULT_TIMEOUT_MAP.get(key);
if (resultPojo != null) {
resultPojo.setHexMessageResult(hexResult);
resultPojo.getCountDownLatch().countDown();
}
}
private CommandPojo getCommandPojo(String key, Object data) {
CrossInfoPO crossInfo = NettyMessageCache.COMMAND_RESULT_SIGN_MAP.get(key);
CommandPojo commandPojo = new CommandPojo();
commandPojo.setCrossId(crossInfo.getId());
commandPojo.setSignalId(crossInfo.getCode());
commandPojo.setSignalIp(crossInfo.getIp());
commandPojo.setPort(crossInfo.getPort());
commandPojo.setResponseMsg(data);
return commandPojo;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
}
}
\ No newline at end of file
...@@ -26,7 +26,7 @@ import java.util.Objects; ...@@ -26,7 +26,7 @@ import java.util.Objects;
@Slf4j @Slf4j
@Component @Component
public class NettyServerHandler extends SimpleChannelInboundHandler<DatagramPacket> { public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
/** /**
* 读取消息 * 读取消息
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment