如何在spring boot中创建Tcp Connection以接受连接?

ami*_*ion 18 java tcp spring-integration spring-boot

我已经完成了这一点并理解我需要创建一个TcpReceivingChannelAdapter接受连接.但我不知道如何处理.

有人可以指导我吗?

Gar*_*ell 15

有关使用XML配置的一些指针,请参阅tcp-client-server示例.

对于Java配置; 这是一个简单的Spring Boot应用程序......

package com.example;

import java.net.Socket;

import javax.net.SocketFactory;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.annotation.Transformer;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNetServerConnectionFactory;
import org.springframework.integration.transformer.ObjectToStringTransformer;
import org.springframework.messaging.MessageChannel;

@SpringBootApplication
public class So39290834Application {

    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext context = SpringApplication.run(So39290834Application.class, args);
        Socket socket = SocketFactory.getDefault().createSocket("localhost", 9999);
        socket.getOutputStream().write("foo\r\n".getBytes());
        socket.close();
        Thread.sleep(1000);
        context.close();
    }

    @Bean
    public TcpNetServerConnectionFactory cf() {
        return new TcpNetServerConnectionFactory(9999);
    }

    @Bean
    public TcpReceivingChannelAdapter inbound(AbstractServerConnectionFactory cf) {
        TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
        adapter.setConnectionFactory(cf);
        adapter.setOutputChannel(tcpIn());
        return adapter;
    }

    @Bean
    public MessageChannel tcpIn() {
        return new DirectChannel();
    }

    @Transformer(inputChannel = "tcpIn", outputChannel = "serviceChannel")
    @Bean
    public ObjectToStringTransformer transformer() {
        return new ObjectToStringTransformer();
    }

    @ServiceActivator(inputChannel = "serviceChannel")
    public void service(String in) {
        System.out.println(in);
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 我不确定你的意思.如果您的意思是在引导中配置Spring Integration组件,我们在参考手册中有一些示例,但尚未针对所有模块.我们有[section](http://docs.spring.io/spring-integration/reference/html/overview.html#programming-tips)来指导您并指出在哪里可以找到有关大多数基础组件的信息元素. (2认同)
  • gradle依赖项:编译'org.springframework.integration:spring-integration-core:4.3.11.RELEASE'compile'org.springframework.integration:spring-integration-ip:4.3.11.RELEASE' (2认同)