简体   繁体   中英

Is it possible to send synchronous messages via Spring WebSocket?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM