Is it possible to send synchronous messages via Spring WebSocket?
Asked Answered
C

1

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.

Crutcher answered 14/9, 2015 at 8:51 Comment(0)
J
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.

Jaquenette answered 25/4, 2019 at 22:24 Comment(1)
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.Jaquenette

© 2022 - 2024 — McMap. All rights reserved.