我想使用websockets实现异步机制。这是想法:
客户端在此主题上注册为订户(假定12232442是id):
this.stompClient.subscribe('/callback/12232442', (messageOutput) => {
let mess = JSON.parse(messageOutput.body);
console.log(mess);
});
完成后,服务器仅发送消息并关闭连接:
stompSession.send("callback/12232442", new MessageOutput());
它应该可以工作,但是这里有个问题:我如何确定另一个客户端不能简单地订阅一个存在但不属于他们的ID?
而且,有没有内置的机制来实现这一目标?
当服务器收到对订阅ID的REST请求时,您可以将新生成的ID存储在Subscription HashMap中。
为了在收到新的订阅请求时进行处理,您可以实现自定义StompEventHandler
,就像这样
@Controller
public class StompEventHandler{
@EventListener
public void handleSubscription(SessionSubscribeEvent event) {
//Get incoming sessionDetails from event.
//get the destination.
// Validate that the destination is present in Subscription HashMap
// and also that no client maps to the topic id.
// Based on the result either send the message or send Unauth message to
client.
}
}
注意,为此您还必须存储有关客户端会话ID的详细信息。无需将消息广播到/topic/callback/<your_id>
,您需要将消息发送到目的地,如下所示:/user/queue/callback/<your_id>
。要发送到这样的目的地,您需要使用simpMessagingTemplate.convertAndSendToUser(username, destination, payload, Headers)
Good Read for this
因此,由于您仅向特定用户的特定会话发送消息,因此您的消息是机密的。
如果要确保您甚至没有来自客户端的订阅,可以在UNSUBSCRIBE
类中向客户端发送StompEventHandler
消息。这将强制退订客户端。Good Read for this