news 2026/1/4 13:42:45

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进行投诉反馈,一经查实,立即删除!
网站建设 2025/12/28 9:49:55

微软和布朗大学最新发现:让AI助手拥有18000多种技能的革命性突破

这项突破性研究由布朗大学的Reza Esfandiarpoor、Stephen H. Bach与微软的Vishwas Suryanarayanan、Vishal Chowdhary、Anthony Aue团队共同完成&#xff0c;于2025年发表。有兴趣深入了解的读者可以通过arXiv:2510.19286v1查询完整论文。这项研究首次展示了如何让AI助手掌握超…

作者头像 李华
网站建设 2025/12/26 0:03:44

MATLAB仿真:二维TOA传感器网络定位与时钟偏差拟合,最小二乘求解

MATLAB仿真 二维的TOA传感器网络定位时钟偏差拟合&#xff0c;最小二乘求解。在传感器网络定位中&#xff0c;基于到达时间&#xff08;TOA&#xff09;的定位方法是一种常用且有效的技术。不过&#xff0c;实际应用里时钟偏差是一个不可忽视的问题&#xff0c;它会影响定位的准…

作者头像 李华
网站建设 2026/1/1 2:18:01

桥梁与隧道安全守护者 抗冰冻型风速监测方案

强风是威胁大型桥梁、高山隧道口安全运营的重要自然因素。实时、准确的风速风向监测是发布预警、采取限行措施的科学依据。FST200-207抗冰冻型超声波风速风向传感器专为此类基础设施的安全监测而设计。 桥梁&#xff0c;特别是悬索桥和斜拉桥&#xff0c;对风荷载非常敏感。在…

作者头像 李华
网站建设 2025/12/27 20:56:51

05-FreeRTOS的内存管理

概述在 FreeRTOS 中&#xff0c;内存管理是连接内核功能与硬件资源的核心环节&#xff0c;直接影响系统的实时性、稳定性和资源利用率。对于基于 STM32 的开发&#xff0c;理解 FreeRTOS 的 内存管理方案是实现可靠嵌入式系统的基础。一、为什么要学习 FreeRTOS 内存管理&#…

作者头像 李华