news 2026/5/1 9:45:37

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/4/30 23:29:03

用长短期记忆网络融合注意力机制做时间序列预测,效果惊人

基于长短期记忆网络融合注意力机制的多变量时间序列预测&#xff0c;预测精度很高。 评价指标&#xff1a; RMSE 0.08024 MSE 0.0064385 MAE 0.071505 MAPE 0.05383在时间序列预测的领域里&#xff0c;多变量时间序列预测一直是个很有挑战性但又特别重要的任务。它广泛应…

作者头像 李华
网站建设 2026/4/21 0:29:27

端到端智驾仿真优选:aiSim破解场景生成、传感器融合核心难题

随着自动驾驶迈入端到端时代&#xff0c;“端到端已来&#xff0c;智驾仿真测试怎么做&#xff1f;”成为研发核心痛点。传统模块化仿真因接口缺失、保真度不足、场景覆盖有限&#xff0c;难以适配端到端模型全链路验证需求。康谋aiSim仿真工具凭借ISO 26262 ASIL-D认证、全链路…

作者头像 李华
网站建设 2026/4/27 14:33:38

汇编语言全接触-33.RichEdit 控件基础知识

有很多人要求我提供关于RichEdit控件的指南&#xff0c;经过这方面的大量编程实践&#xff0c;我想我终于可以开写关于RichEdit控件的指南了。诺&#xff0c;这个就是第一篇RichEdit指南。本指南将会描述涉及到RichEdit的几乎所有方面&#xff0c;起码是我所知道的关于它的所有…

作者头像 李华
网站建设 2026/4/26 15:41:39

【翼型】基于非主导排序遗传算法的翼型形状优化附Matlab代码

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

作者头像 李华
网站建设 2026/5/1 8:43:29

基于金枪鱼群优化算法优化概率神经网络分类(TSO-PNN)附Matlab代码

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

作者头像 李华
网站建设 2026/4/26 3:35:52

FT8440B输出12V350MA,18V300MA 非隔离电源方案 典型应用电路

FT8440B是离线非隔离 Buck 架构、集成 650V 高压启动与功率开关的电流模 PWM 控制器&#xff0c;主打高精度恒压&#xff08;3%&#xff09;、低成本与极简外围&#xff0c;适合 90–264Vac 输入、5–18V 输出、中小功率&#xff08;典型 12V/450mA、18V/300mA&#xff09;的恒…

作者头像 李华