Search code examples
springspring-bootspring-integrationtcpsocket

Spring Integration TCP Server to Client request response


I've a use case where I need to make requests to an external system using TCP socket and wait for response. I know that Spring Integration Outbound Gateway can be used if I'm connected as a client. But as per the requirement of the external system, I need to start my service as a TCP server and external system will create multiple active connections to my service. Now whenever I needed, I should use one of the active connections to make a request to the external system.

I know the alternative approach of Adapters, but I think they are not Direct Channel and will be working asynchronously. And I will have to choose one of the connections manually in a thread safe way. Does Spring Integration provides any synchronous and thread safe approach for the Servlet to Client request/response pattern? Or is it better to go with plain java socket connection in this scenario?

TIA

Tried using Spring integration gateway, but for server it only supports Inbound Gateway


Solution

  • Yes, you have to use Collaborating Outbound and Inbound Channel Adapters: https://docs.spring.io/spring-integration/reference/ip/correlation.html.

    You still can achieve a sync logic from your application perspective via @MessagingGateway to produce a message to the TcpSendingMessageHandler which chosen ip_connectionId. Send this message into an aggregator as well. And then on receiving from the TcpReceivingChannelAdapter you send that message to that aggregator for correlation between request and reply to complete the group. The result of this aggregator must go to the replyChannel of the request message to relay it back into the original @MessagingGateway as a return value.

    We probably don't have such a sample, but I believe that your idea withe plain Java sockets would lead to similar correlation solution.

    Not sure what information you transfer over the network to be able to correlate reply back. If you can do that only based on the mentioned ip_connectionId, then you need to implement connection pool logic to have an exclusive access to them until reply comes back on this connection. Then you indeed can correlated in the aggregator using this ip_connectionId indication.