6

I have a Spring application and it sends messages to another server asynchronously via Spring WebSocket . But for a specific case I need to send a message synchronously, I should continue the process with incoming response from the server.

I don’t want to make an HTTP call only for this process because there is already an open TCP connection, and I want to use it.

For example in Tyrus WebSocket implementation it is possible to send message synchronously or asynchronously via

session.getBasicRemote().sendText(message);
session.getAsyncRemote().sendText(message);

Related Tyrus documentation link.

Btw, I don’t use a sub-protocol like STOMP with Spring WebSocket.

azizunsal
  • 2,074
  • 1
  • 25
  • 33

1 Answers1

0

You can add a custom pattern to a message that needs to be answered.

Suppose you want to send form server A to server B:

sendToB("REPLY ME!");

Before you actually send the message, server A put a custom phrase in it, like:

sendToB("REQUEST:1234" + "#$#" + "REPLY-ME!");

When the server B receive the message:

String[] parts = message.split("#$#");
if (parts.length > 0) {
    String[] keyValue = parts[0].split(":");
    sendToA("RESPONSE:" + keyValue[1] + "#$#" + "CALM DOWN!");
}

Finally, server A receive the message:

"RESPONSE:1234#$#CALM DOWN!"

Then the synchronous message is done.

Hugo Sartori
  • 560
  • 6
  • 21
  • This is kind of a sub-protocol, but simple enougth. Of couse this is a pseudo-java code, the actual implementation would have a bit more lines of code and you can optimize the REQUEST/RESPONSE string and the command/message separator to be more efficient. – Hugo Sartori Apr 25 '19 at 22:24