当前位置: 首页 > news >正文

springboot框架对接物联网,配置TCP协议依赖,与设备通信,让TCP变的如此简单

最近在使用 Spring Boot 对接物联网设备,需要通过 TCP 协议进行通信。调研过程中发现,如果使用 Netty 框架并集成到 Spring Boot 中,配置和维护相对较为复杂。综合考虑后,最终选择了 Spring Integration 提供的 TCP/UDP 模块来实现相关功能,整体集成更加简洁,也更符合 Spring 生态的使用习惯。
第一步:
引入依赖

<dependency><groupId>org.springframework.integration</groupId><artifactId>spring-integration-ip</artifactId></dependency>

第二步:
提供两个tcp服务端类文件,这两个类文件大家按需选择即可。
第一个类文件:
单向接收tcp客户端数据:

package com.testweb.testweb.tcp.web;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.integration.annotation.ServiceActivator;importorg.springframework.integration.channel.DirectChannel;importorg.springframework.integration.ip.tcp.TcpReceivingChannelAdapter;importorg.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;importorg.springframework.integration.ip.tcp.connection.TcpNioServerConnectionFactory;importorg.springframework.integration.ip.tcp.serializer.ByteArrayCrLfSerializer;importorg.springframework.messaging.Message;importorg.springframework.messaging.MessageChannel;importjava.nio.charset.StandardCharsets;@Slf4j @Configuration public class TcpServerConfig{@Value("${tcp.server.port:7788}")private int port;/** *1. TCP 连接工厂(服务端) */ @Bean public AbstractServerConnectionFactoryserverConnectionFactory(){TcpNioServerConnectionFactory factory=new TcpNioServerConnectionFactory(port);// 关键:拆包 / 粘包解决方案(行结束符) // 按换行符(\r\n 或\n)拆包,常用于文本协议 ByteArrayCrLfSerializer serializer=new ByteArrayCrLfSerializer();// 二进制协议示例:长度头 + 消息内容(常用于物联网) // ByteArrayLengthHeaderSerializer serializer=// new ByteArrayLengthHeaderSerializer();factory.setSerializer(serializer);factory.setDeserializer(serializer);factory.setUsingDirectBuffers(true);returnfactory;}/** *2. 接收同步通道 */ @Bean public MessageChanneltcpReceiveChannel(){returnnew DirectChannel();}/** *3. TCP 入站适配器(只接收) */ @Bean public TcpReceivingChannelAdapter tcpInboundAdapter(AbstractServerConnectionFactory factory, MessageChannel tcpReceiveChannel){TcpReceivingChannelAdapter adapter=new TcpReceivingChannelAdapter();adapter.setConnectionFactory(factory);adapter.setOutputChannel(tcpReceiveChannel);returnadapter;}/** *4. 业务处理器(单向接收,不能给客户端回复) */ @ServiceActivator(inputChannel="tcpReceiveChannel")public void handleMessage(Message<byte[]>message){String data=new String(message.getPayload(), StandardCharsets.UTF_8);String connectionId=(String)message.getHeaders().get("ip_connectionId");log.info("收到 TCP 数据: {}", data);log.info("来自连接: {}", connectionId);// TODO 业务逻辑处理}}

第二个类文件:
双向类文件:接收客户端消息并回复

package com.testweb.testweb.tcp.web;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.integration.annotation.ServiceActivator;importorg.springframework.integration.channel.DirectChannel;importorg.springframework.integration.ip.tcp.TcpReceivingChannelAdapter;importorg.springframework.integration.ip.tcp.TcpSendingMessageHandler;importorg.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;importorg.springframework.integration.ip.tcp.connection.TcpNioServerConnectionFactory;importorg.springframework.integration.ip.tcp.serializer.ByteArrayCrLfSerializer;importorg.springframework.messaging.Message;importorg.springframework.messaging.MessageChannel;importjava.nio.charset.StandardCharsets;@Slf4j @Configuration public class TcpServerReplyConfig{@Value("${tcp.server.reply.port:7799}")// 与单向服务端端口区分 private int port;// 回复通道 @Autowired @Qualifier("tcpReplySendChannel")private MessageChannel tcpReplySendChannel;/** *1. TCP 连接工厂(服务端) */ @Bean public AbstractServerConnectionFactoryreplyServerConnectionFactory(){TcpNioServerConnectionFactory factory=new TcpNioServerConnectionFactory(port);// 关键:拆包 / 粘包解决方案 // 使用换行符拆包(文本协议)或长度头(物联网二进制协议) ByteArrayCrLfSerializer serializer=new ByteArrayCrLfSerializer();// ByteArrayLengthHeaderSerializer serializer=// new ByteArrayLengthHeaderSerializer();factory.setSerializer(serializer);factory.setDeserializer(serializer);factory.setUsingDirectBuffers(true);returnfactory;}/** *2. 接收通道 */ @Bean public MessageChanneltcpReplyReceiveChannel(){returnnew DirectChannel();}/** *3. TCP 入站适配器(接收客户端消息) */ @Bean public TcpReceivingChannelAdapter tcpReplyInboundAdapter(AbstractServerConnectionFactory replyServerConnectionFactory, MessageChannel tcpReplyReceiveChannel){TcpReceivingChannelAdapter adapter=new TcpReceivingChannelAdapter();adapter.setConnectionFactory(replyServerConnectionFactory);adapter.setOutputChannel(tcpReplyReceiveChannel);returnadapter;}/** *4. TCP 出站通道(用于回复客户端) */ @Bean("tcpReplySendChannel")public MessageChanneltcpReplySendChannel(){returnnew DirectChannel();}/** *5. 出站适配器(发送回复) */ @Bean @ServiceActivator(inputChannel="tcpReplySendChannel")public TcpSendingMessageHandler tcpReplySender(AbstractServerConnectionFactory replyServerConnectionFactory){TcpSendingMessageHandler sender=new TcpSendingMessageHandler();sender.setConnectionFactory(replyServerConnectionFactory);returnsender;}/** *6. 业务处理器:接收客户端消息并回复 */ @ServiceActivator(inputChannel="tcpReplyReceiveChannel")public void handleReplyMessage(Message<byte[]>message){String data=new String(message.getPayload(), StandardCharsets.UTF_8);String connectionId=(String)message.getHeaders().get("ip_connectionId");log.info("收到客户端消息: {}", data);log.info("来自连接: {}", connectionId);// 业务逻辑处理完后发送回复 String reply="服务端已经收到消息,现在给客户端回复: "+ data;tcpReplySendChannel.send(org.springframework.messaging.support.MessageBuilder .withPayload(reply.getBytes(StandardCharsets.UTF_8)).setHeader("ip_connectionId", connectionId).build());}}

这两个配置文件 大家可以按需选择。第一个类文件就是服务端只负责接收,不会给客户端反馈
第二个类文件,接收后会反馈,如果在使用中发现有需要完善的地方,也欢迎大家留言~

http://www.cnnetsun.cn/news/115296.html

相关文章:

  • 微软和布朗大学最新发现:让AI助手拥有18000多种技能的革命性突破
  • MATLAB仿真:二维TOA传感器网络定位与时钟偏差拟合,最小二乘求解
  • 【参数辨识】基于卡尔曼滤波(KF)估计离散线性系统对垂直起降(VTOL)飞行器的鲁棒辨识附matlab代码
  • 桥梁与隧道安全守护者 抗冰冻型风速监测方案
  • 05-FreeRTOS的内存管理
  • 基于改进蛇优化算法(GOSO/ISO)优化随机森林数据回归预测模型(含初始化种群混沌映射、减法...
  • 基于大数据的人脸识别系统设计与实现开题报告
  • 车载 Android 系统稳定性问题全解析:从性能到黑屏的排查指南
  • 气象在线监测系统助力智慧环境管理,金叶仪器专业气象监测解决方案
  • 【TVM 教程】交叉编译与 RPC
  • 腾讯云国际站代理商的QAPM服务能提供哪些专属服务?
  • 网安副业怎么选?漏洞挖掘、技术博客、竞赛奖金实战,哪个更适配你?
  • 量子计算验证方法:软件测试从业者的转型指南
  • 突破 Oracle/MySQL 瓶颈:金仓数据库以三重革新,筑牢业务转型 “数据底座”
  • 【学习神器】NotebookLM“播客”功能实战指南:四六级、考研党高效复习秘籍
  • 如何解决 pip install 网络报错 ERROR: No matching distribution found for requests
  • 12 Ways to Find User Account Info and Login Details in Linux
  • 紧急警告:错误的导出格式正毁掉你的量子实验成果,速查正确方式
  • 35 岁职场焦虑蔓延?为什么网络安全行业越老越值钱?
  • 内网渗透实战干货:12 个优质靶场平台精选,附避坑指南 + 实操技巧合集!
  • 新型电力系统下多分布式电源接入配电网承载力评估方法研究附Matlab代码
  • 50天学习FPGA第16天-verilog的模块与端口
  • 50天学习FPGA第15天-verilog基本概念
  • 基于Docker容器化部署Lsky Pro私有图床系统
  • GRPO不香了?小米ICPO横空出世,专治大模型“不会思考”,推理能力飙升!
  • Windows找不到xenroll.dll文件 如何下载修复?
  • 软件测试文档标准化编写指南
  • Paperzz AI:毕业论文写作的 “隐形助攻”,让学术输出告别 “抓瞎”
  • BypassAV通过Patch白文件实现Bypass,没有添加其他免杀手法
  • 鸿蒙:一个操作系统的生态远征与多行业渗透之路