Spring integration - Sending message from TCP server with gateway

Viewed 41

I am attempting to create a microservice which acts as both server and client for testing purposes.

My client-side will connect as client-mode connected to a remote microservice which connects at the same time with my server-side, so I can send messages being both client or server and get their replies.

Client side of μs1 <-> Server side of μs2 <-> Client side of μs2 <-> Server side of μs1

I have tried to make an incoming and outgoing integration flow for each side (see the client one below) with TcpSendingMessageHandler and TcpReceivingChannelAdapter but it's not possible to retrieve the reply sent by their counterparts as they are one-way component and don't wait for any replies to produce to the replyChannel header for my TcpClientGateway, so there is not response back.

    @Bean
public IntegrationFlow incomingClient(final TcpReceivingChannelAdapter tcpReceivingChannelAdapter,
                                      TcpServerEndpoint tcpServerEndpoint) {

    return IntegrationFlows
            .from(tcpReceivingChannelAdapter)
            .handle(message -> { LOGGER.info("RECEIVING ON CLIENT: {}", tcpServerEndpoint.processMessage((byte[]) message.getPayload()));})
            .get();
}


@Bean
public IntegrationFlow outgoingClient(final MessageChannel outboundChannel, final TcpSendingMessageHandler tcpSendingClientMessageHandler) {

    return IntegrationFlows
            .from(outboundChannel)
            .handle(tcpSendingClientMessageHandler)
            .get();
}

As far as I know i need to use TcpInboundGateway and TcpOutboundGateway components as they can manage these replies I need to get.

¿How could I implement this so once each side is connected with each other I can start sending a message with my server side and get the reply? ¿Is it possible to send a message being a server with an InboundGateway?

I need to send messages from any side of this flow no matter who starts the communication because it could be anyone.

Thanks.

1 Answers

You can't do that with gateways (unless you have two sets); for arbitrary peer to peer communication over a single connection, you have to use collaborating channel adapters. https://docs.spring.io/spring-integration/docs/current/reference/html/ip.html#ip-collaborating-adapters

When you receive a message, you will need to decide if it's a request or a reply. If it's a reply, you can send it to an aggregator, where you previously sent a copy of the request.

You will need some mechanism to correlate replies to requests; since TCP has no concept of a header, it would have to be something in the data.

There's a partial solution in the samples repo https://github.com/spring-projects/spring-integration-samples/tree/main/intermediate/tcp-client-server-multiplex - it is old and uses XML configuration, but the concepts are the same.

Related