SpringBoot快速搭建TCP服务端和客户端
    		       		warning:
    		            这篇文章距离上次修改已过425天,其中的内容可能已经有所变动。
    		        
        		                
                以下是一个简单的Spring Boot TCP服务器和客户端的示例。
TCP服务器端 (Spring Boot):
- 添加依赖 
spring-boot-starter-integration和spring-boot-starter-web到pom.xml。 - 配置服务器端口和TCP连接工厂。
 - 创建TCP连接接收器。
 - 启动Spring Boot应用程序。
 
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.TcpNetServerConnectionFactory;
import org.springframework.integration.ip.tcp.serializer.ByteArraySerializer;
 
@Configuration
public class TcpServerConfig {
 
    @Bean
    public TcpNetServerConnectionFactory serverConnectionFactory() {
        TcpNetServerConnectionFactory factory = new TcpNetServerConnectionFactory(12345);
        factory.setSerializer(new ByteArraySerializer());
        factory.setDeserializer(new ByteArraySerializer());
        return factory;
    }
 
    @Bean
    public TcpInboundGateway tcpInboundGateway() {
        TcpInboundGateway gateway = new TcpInboundGateway();
        gateway.setConnectionFactory(serverConnectionFactory());
        return gateway;
    }
 
    @ServiceActivator
    public void clientMessageHandler() {
        // 处理接收到的消息
    }
}TCP客户端 (Spring Boot):
- 添加依赖 
spring-boot-starter-integration和spring-boot-starter-web到pom.xml。 - 配置服务器地址和端口。
 - 发送消息。
 - 启动Spring Boot应用程序。
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.ip.tcp.TcpOutboundGateway;
import org.springframework.integration.ip.tcp.TcpNetClientConnectionFactory;
import org.springframework.integration.ip.tcp.serializer.ByteArraySerializer;
 
@Configuration
public class TcpClientConfig {
 
    @Bean
    public TcpNetClientConnectionFactory clientConnectionFactory() {
        TcpNetClientConnectionFactory factory = new TcpNetClientConnectionFactory("localhost", 12345);
        factory.setSerializer(new ByteArraySerializer());
        factory.setDeserializer(new ByteArraySerializer());
        return factory;
    }
 
    @Bean
    @ServiceActivator
    public TcpOutboundGateway tcpOutboundGateway() {
        Tc           
评论已关闭