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

spring通过Spring Integration实现tcp通信

1:Spring Integration TCP 核心概念

        Spring Integration TCP 模块主要提供了以下组件:

                连接工厂 (ConnectionFactory): 负责创建和管理 TCP 连接。分为客户端 (TcpNetClientConnectionFactory) 和服务端 (TcpNetServerConnectionFactory) 两种类型

        通道适配器 (Channel Adapter): 用于单向通信。

        入站适配器 (TcpReceivingChannelAdapter): 接收 TCP 数据并通过通道发送到应用。

        出站适配器 (TcpSendingMessageHandler): 将消息载荷通过 TCP 连接发送出去。

        消息网关 (Gateway): 用于请求-响应模式的双向通信。

        入站网关 (TcpInboundGateway): 处理来自客户端的请求并返回响应。

        出站网关 (TcpOutboundGateway): 向服务器发送请求并等待响应。

2:代码实现

1)添加依赖

<!-- spring-integration -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-integration</artifactId><version>2.5.15</version>
</dependency>
<dependency><groupId>org.springframework.integration</groupId><artifactId>spring-integration-ip</artifactId><version>5.5.18</version>
</dependency>

2)创建tcp服务端配置

package **.**;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.ip.tcp.TcpInboundGateway;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNioServerConnectionFactory;
import org.springframework.integration.ip.tcp.serializer.ByteArrayLfSerializer; // 用于处理消息边界@Configuration
public class TcpServerConfig {/*** 创建TCP服务器连接工厂* 负责创建和管理服务器端的TCP连接** @return AbstractServerConnectionFactory TCP服务器连接工厂实例*/@Beanpublic AbstractServerConnectionFactory serverConnectionFactory() {// 创建NIO服务器连接工厂,监听端口12345TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(12345);// 设置序列化器:使用LF(换行符)作为消息分隔符的字节数组序列化器// 这是解决TCP粘包/拆包问题的关键配置factory.setSerializer(new ByteArrayLfSerializer());// 设置反序列化器:同样使用LF作为分隔符factory.setDeserializer(new ByteArrayLfSerializer());// 可选配置:设置读取超时时间(毫秒)// factory.setSoTimeout(5000);// 可选配置:设置服务器 backlog(等待连接队列大小)// factory.setBacklog(100);return factory;}/*** 创建TCP入站网关* 负责处理来自客户端的TCP连接请求,并将请求转发到指定的消息通道** @param connectionFactory TCP连接工厂* @return TcpInboundGateway TCP入站网关实例*/@Beanpublic TcpInboundGateway tcpInGate(AbstractServerConnectionFactory connectionFactory) {TcpInboundGateway gateway = new TcpInboundGateway();// 设置连接工厂gateway.setConnectionFactory(connectionFactory);// 设置请求通道名称,接收到的消息将发送到此通道gateway.setRequestChannelName("tcpServerInChannel");// 可选:设置错误通道名称,用于处理连接或处理过程中出现的错误// gateway.setErrorChannelName("tcpErrorChannel");return gateway;}/*** 服务端消息处理器* 处理从TCP连接接收到的消息,并返回响应** @param messagePayload 接收到的消息字节数组* @return byte[] 响应字节数组*/@ServiceActivator(inputChannel = "tcpServerInChannel")public byte[] processRequest(byte[] messagePayload) {// 将字节数组转换为字符串String request = new String(messagePayload);// 打印接收到的消息(实际应用中应替换为业务逻辑)System.out.println("Server received: " + request);// 处理请求并生成响应(这里简单返回处理后的字符串)return ("Processed: " + request).getBytes();}
}

3)创建tcp客户端配置

package **.**;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.ip.tcp.TcpOutboundGateway;
import org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNetClientConnectionFactory;
import org.springframework.integration.ip.tcp.serializer.ByteArrayLfSerializer;@Configuration
public class TcpClientConfig {/*** 创建TCP客户端连接工厂* 负责创建和管理客户端的TCP连接** @return AbstractClientConnectionFactory TCP客户端连接工厂实例*/@Beanpublic AbstractClientConnectionFactory clientConnectionFactory() {// 创建TCP客户端连接工厂,连接到localhost:12345TcpNetClientConnectionFactory factory = new TcpNetClientConnectionFactory("localhost", 12345);// 设置序列化器:使用LF(换行符)作为消息分隔符的字节数组序列化器// 与服务端的序列化器配置必须一致factory.setSerializer(new ByteArrayLfSerializer());// 设置反序列化器:同样使用LF作为分隔符factory.setDeserializer(new ByteArrayLfSerializer());// 设置为长连接(false),而不是每次发送后关闭连接(true)factory.setSingleUse(false);return factory;}/*** 创建TCP出站网关* 负责通过TCP连接发送消息并接收响应** @param connectionFactory TCP连接工厂* @return TcpOutboundGateway TCP出站网关实例*/@Bean@ServiceActivator(inputChannel = "tcpClientOutChannel")public TcpOutboundGateway tcpOutGate(AbstractClientConnectionFactory connectionFactory) {TcpOutboundGateway gateway = new TcpOutboundGateway();// 设置连接工厂gateway.setConnectionFactory(connectionFactory);// 可选:设置是否等待响应(true)或只是发送消息(false)// gateway.setRemoteTimeout(5000); // 设置等待响应的超时时间return gateway;}/*** 消息网关接口* 提供类型安全的接口用于发送TCP消息* Spring Integration会自动实现此接口*/@MessagingGateway(defaultRequestChannel = "tcpClientOutChannel")public interface TcpClientGateway {/*** 发送消息到TCP服务器并接收响应** @param message 要发送的消息字节数组* @return byte[] 服务器响应的字节数组*/byte[] send(byte[] message);}
}

4)处理消息

        在服务端,使用 @ServiceActivator 注解的方法来处理接收到的消息并返回响应。

        在客户端,通过注入的 MessagingGateway 接口来发送消息并接收响应:

        

package **.**;import com.ruoyi.lxsjgl.config.TcpClientConfig;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;@RestController
@RequestMapping("/tcp")
public class TcpClientController {// 注入TCP客户端网关@Resourceprivate TcpClientConfig.TcpClientGateway tcpClientGateway;/*** REST接口:通过TCP发送消息** @param message 要发送的消息内容* @return String 包含服务器响应的结果字符串*/@GetMapping("/sendMessage")public String sendMessageOverTcp(@RequestParam String message) {try {// 通过TCP客户端网关发送消息byte[] responseBytes = tcpClientGateway.send(message.getBytes());// 将响应字节数组转换为字符串String response = new String(responseBytes);// 返回格式化后的响应return "Server responded: " + response;} catch (Exception e) {// 处理异常情况return "Error sending message: " + e.getMessage();}}}


文章转载自:

http://NihJCf5i.ssjry.cn
http://r6ixGpqF.ssjry.cn
http://FdjJ5bng.ssjry.cn
http://w4QT09ii.ssjry.cn
http://WZyPKMEP.ssjry.cn
http://94Z7bvcG.ssjry.cn
http://q4Vdsryj.ssjry.cn
http://QCFrTszk.ssjry.cn
http://GdBjlrES.ssjry.cn
http://6WNjcNe8.ssjry.cn
http://YPsPxfSi.ssjry.cn
http://VQMjWCS2.ssjry.cn
http://L0Bf4HQb.ssjry.cn
http://5MoGcE3V.ssjry.cn
http://2LRvXTZN.ssjry.cn
http://rz58Zy7G.ssjry.cn
http://QqvaslRl.ssjry.cn
http://kSDLfZeE.ssjry.cn
http://U3bu2zPF.ssjry.cn
http://wPeidPG1.ssjry.cn
http://EoWpuJau.ssjry.cn
http://nE4fzx9E.ssjry.cn
http://ds3C319n.ssjry.cn
http://UQ3rqVmR.ssjry.cn
http://nqsenUCw.ssjry.cn
http://530UylRH.ssjry.cn
http://kM26LJC9.ssjry.cn
http://z9QrayfB.ssjry.cn
http://NIfEkgrv.ssjry.cn
http://mKw9iVIw.ssjry.cn
http://www.dtcms.com/a/386898.html

相关文章:

  • 改革企业治理架构,构建国有企业全面预算管理体系
  • 网络概述学习
  • VRRP 实验
  • confulence平台
  • 非许可型区块链
  • 如何使用词嵌入模型
  • 从一个想法到上线:Madechango项目架构设计全解析
  • pytest入门
  • 设计模式第二章(装饰器模式)
  • ​​解决大模型幻觉全攻略:理论、技术与落地实践​
  • qt QCandlestickSeries详解
  • 量化研究--高频日内网格T0策略研究
  • [Dify] 自动摘要与精炼:构建内容浓缩型工作流的实践指南
  • Windows安装mamba最佳实践(WSL ubuntu丝滑版)
  • 黑马头条_SpringCloud项目阶段一:环境搭建(Mac版本)
  • Java 设计模式全景解析
  • 【Python】OS模块操作目录
  • 深度学习基本模块:LSTM 长短期记忆网络
  • 初始化Vue3 项目
  • 耕地质量评价
  • MeloTTS安装实践
  • 国产化芯片ZCC3790--同步升降压控制器的全新选择, 替代LT3790
  • LeetCode 977.有序数组的平方
  • 佳易王个体诊所中西医电子处方管理系统软件教程详解:开方的时候可一键导入配方模板,自由添加模板
  • C#实现WGS-84到西安80坐标系转换的完整指南
  • rabbitmq面试题总结
  • 【Java初学基础】⭐Object()顶级父类与它的重要方法equals()
  • C语言初尝试——洛谷
  • Kaleidoscope for Mac:Mac 平台文件与图像差异对比的终极工具
  • LeetCode 刷题【80. 删除有序数组中的重复项 II】