Search code examples
springtcpspring-integration

Spring Integration TCP Multiple sockets on client side to one server address


Requisites:

  • I should open multiple sockets/connections to the same server IP and Port.
  • I should detect from which connection a request has come and
    reroute the response to the same connection
  • A connection is represented as server Ip and port + client Ip and port
  • Each connection has to be single-use=false, it is expected to have multiple request/replies

I'm using collaborating TcpReceivingChannelAdapter and TcpSendingMessageHandler with TcpNetClientConnectionFactory.

And IntegrationFlow for generating those connections dynamically.


How to create multiple sockets for TcpNetClientConnectionFactory that all point to the same Host and port?

I know how to set destination with new TcpNetClientConnectionFactory(host, port). But I'm unable to see or find how to affect which port is used

Should it be done with multiple TcpNetClientConnectionFactory each being bound to one inbound and outbound TCP adapter?

How can I set the local port for those connections? or at least how to obtain it?

I don't seem to find any documentantion about this option. The most similar would be This question


Solution

  • You need a separate connection factory/adapters for each.

    See TCP Connection Events.

    Use an ApplicationListener or @EventListener to receive TcpConnectionEvents.

    The event has getConnectionId() which contains both the local and remote port; the event also has the connection factory bean name.

    Or you can cast getSource() to TcpConnection and call getPort() (but you should not otherwise interact with the TcpConnection object.