且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring Boot TCP客户端

更新时间:2022-06-15 22:36:12

此应用程序既是客户端又是服务器.

This application is both the client and the server.

该问题专门涉及如何使用Spring Integration编写服务器端(接受连接).

That question was specifically about how to write the server side (accept the connection), using Spring Integration.

main()方法只是连接到服务器端的测试.它使用标准的Java套接字API;它也可以编写为在客户端使用Spring Integration组件.

The main() method is simply a test that connects to the server side. It uses standard Java sockets APIs; it could also have been written to use Spring Integration components on the client side.

顺便说一句,您不必使用XML来编写Spring Integration应用程序,您可以使用注释对其进行配置,也可以使用Java DSL.阅读文档.

BTW, you don't have to use XML to write a Spring Integration application, you can configure it with annotations, or use the Java DSL. Read the documentation.

编辑

使用Java DSL的客户端/服务器示例

@SpringBootApplication
public class So54057281Application {

    public static void main(String[] args) {
        SpringApplication.run(So54057281Application.class, args);
    }

    @Bean
    public IntegrationFlow server() {
        return IntegrationFlows.from(Tcp.inboundGateway(
                    Tcp.netServer(1234)
                        .serializer(codec()) // default is CRLF
                        .deserializer(codec()))) // default is CRLF
                .transform(Transformers.objectToString()) // byte[] -> String
                .<String, String>transform(p -> p.toUpperCase())
                .get();
    }

    @Bean
    public IntegrationFlow client() {
        return IntegrationFlows.from(MyGateway.class)
                .handle(Tcp.outboundGateway(
                    Tcp.netClient("localhost", 1234)
                        .serializer(codec()) // default is CRLF
                        .deserializer(codec()))) // default is CRLF
                .transform(Transformers.objectToString()) // byte[] -> String
                .get();
    }

    @Bean
    public AbstractByteArraySerializer codec() {
        return TcpCodecs.lf();
    }

    @Bean
    @DependsOn("client")
    ApplicationRunner runner(MyGateway gateway) {
        return args -> {
            System.out.println(gateway.exchange("foo"));
            System.out.println(gateway.exchange("bar"));
        };
    }

    public interface MyGateway {

        String exchange(String out);

    }

}

结果

FOO
BAR