Spring Integration Tcp project

Viewed 42

I have a project that part of it is using Tcp connection, the case is as per below , I will also include a screen shot.

We have two clients, client 1 and client 2 those are conveyor belts so if we receive data on client one input we should send the reply to client 2 output and vise vers, I'm sure we can do it using Spring integration Tcp and probably getways. Am I approaching correctly Tcp integration at this case?

Yet I do not have code implementation but started to put something on it.

enter image description here

1 Answers

Sounds like you implementing a chat (or similar user-to-user) communication.

No, gateways won't help you here.

You need to have a TcpReceivingChannelAdapter and TcpSendingMessageHandler connected to the same AbstractServerConnectionFactory. The TcpSendingMessageHandler is registered as a TcpSender with that connection and all the sending connections are stored in the Map<String, TcpConnection> connections. When we produce a message to this MessageHandler, it tries to consult that registry like this:

private void handleMessageAsServer(Message<?> message) {
    // We don't own the connection, we are asynchronously replying
    String connectionId = message.getHeaders().get(IpHeaders.CONNECTION_ID, String.class);
    TcpConnection connection = null;
    if (connectionId != null) {
        connection = this.connections.get(connectionId);
    }
    if (connection != null) {

So, on the receiving side (TcpReceivingChannelAdapter and its sub-flow) you need to ensure somehow that you really set a proper IpHeaders.CONNECTION_ID header for producing so-called reply in the end to a desired client.

You probably can react for the TcpConnectionOpenEvent via @EventListener and register some business key with the connectionId for the future correlation. When you send a message, you supply that target user business key, in the TcpReceivingChannelAdapter sub-flow you take that business key and obtain a desired connectionId from you registry. And enrich it into the IpHeaders.CONNECTION_ID header for automatic logic in the TcpSendingMessageHandler.

When TcpConnectionCloseEvent happens you have to remove its respective entry from your custom registry.

Since TCP/IP comes without headers support there is no any out-of-the-box mechanism to implement such a correlation feature.

Although TcpConnectionOpenEvent might not be enough for you since there is no any business info when connection is established. Perhaps you would need to implement some hand-shake logic in the TcpReceivingChannelAdapter flow to distinguish a real message and connection metadata for registering in the custom registry.

See more info in the docs: https://docs.spring.io/spring-integration/docs/current/reference/html/ip.html#ip-correlation

It might be also better for your use-case to look into a WebSocket support: https://docs.spring.io/spring-integration/docs/current/reference/html/web-sockets.html#web-sockets

Related