news 2026/6/21 15:16:40

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

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
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());}}

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

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/20 20:08:17

上海交大造出手机AI助手ColorAgent:不只是工具,更像贴心伙伴

这项突破性研究由上海交通大学与OPPO研究院联合完成&#xff0c;研究成果发表于2025年10月22日的arXiv预印本平台&#xff0c;论文编号为arXiv:2510.19386v1。研究团队由来自上海交通大学的李宁、吴正、张伟明等多位学者&#xff0c;以及OPPO研究院的林旗强、莫晓芸、赵音等专家…

作者头像 李华
网站建设 2026/6/20 11:09:51

机器视觉介绍

机器视觉的定义机器视觉&#xff08;Machine Vision&#xff09;是指通过计算机和图像处理技术模拟人类视觉功能&#xff0c;实现对物体识别、测量、定位和分析的自动化系统。广泛应用于工业检测、自动驾驶、医疗影像等领域。机器视觉的核心技术图像采集 通过摄像头、工业相机或…

作者头像 李华
网站建设 2026/6/17 16:04:30

基于鲹鱼优化算法(GTO)优化Canopy聚类附matlab代码

✅作者简介&#xff1a;热爱科研的Matlab仿真开发者&#xff0c;擅长数据处理、建模仿真、程序设计、完整代码获取、论文复现及科研仿真。 &#x1f34e; 往期回顾关注个人主页&#xff1a;Matlab科研工作室 &#x1f34a;个人信条&#xff1a;格物致知,完整Matlab代码获取及仿…

作者头像 李华
网站建设 2026/6/14 9:40:01

IMU和GPS ekf融合定位 从matlab到c++代码实现 基于位姿状态方程

IMU和GPS ekf融合定位 从matlab到c代码实现 基于位姿状态方程&#xff0c;松耦合 文档且详细 蹲在实验室捯饬了三天咖啡机之后&#xff0c;我终于把IMU和GPS的EKF融合算法从Matlab搬到了C。这事儿就像把乐高积木从说明书模式切换到自由创作模式——你知道原理是对的&#xff0…

作者头像 李华
网站建设 2026/6/20 8:56:31

无人值守地区的可靠选择 的远程监测能力

对于环境恶劣的高山、海岛、边境、自然保护区等无人值守的边远地区&#xff0c;建立自动气象站面临供电难、维护难、环境苛刻度高等多重挑战。FST200-207抗冰冻型超声波风速风向传感器的低功耗、高可靠和易集成的特点&#xff0c;使其成为此类应用的理想解决方案。 超声波风速…

作者头像 李华
网站建设 2026/6/20 15:31:25

linux部署分布式redis集群保姆级教程

一、Redis常用的三种集群模式主从&#xff08;单体架构项目&#xff09;通过持久化功能&#xff0c;Redis保证了即使在服务器重启的情况下也不会丢失&#xff08;或少量丢失&#xff09;数据&#xff0c;因为持久化会把内存中数据保存到硬盘上&#xff0c;重启会从硬盘上加载数…

作者头像 李华