我想使用websockets实现异步机制。 这是想法:
客户端在该主题上注册为订户(假设ID为12232442):
this.stompClient.subscribe('/callback/12232442', (messageOutput) => {
let mess = JSON.parse(messageOutput.body);
console.log(mess);
});
完成后,服务器仅发送消息并关闭连接:
stompSession.send("callback/12232442", new MessageOutput());
它应该可以工作,但要注意的是:我如何确定另一个客户端不能简单地订阅一个存在但不属于他们的ID?
还有,有没有内置的机制来实现这一目标?
答案 0 :(得分:1)
当服务器收到针对订阅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