[英]private messages spring websocket
我正在學習 spring websocket 並且我堅持如何使用@DestinationVariable("username")
向特定用戶發送消息這是我的代碼
configuration
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketContextConfig extends AbstractSessionWebSocketMessageBrokerConfigurer<ExpiringSession> {
@Override
protected void configureStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws-cfg").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableStompBrokerRelay("/queue/","/topic","/exchange/")
.setRelayHost("localhost");
registry.setApplicationDestinationPrefixes("/app");
}
}
控制器
@MessageMapping("/chat.private.{username}")
public void filterPrivateMessage(@Payload Message message, @DestinationVariable("username") String username, Principal principal) {
this.simpMessagingTemplate.convertAndSendToUser(username, "/queue/chat.message", message);
}
客戶端代碼
var stomp = null;
stomp = Stomp.over(new SockJS("/ws-cfg"));
stomp.connect('guest', 'guest', function(frame) {
stomp.subscribe("/user/queue/chat.message", function (frame) {
dysplayMessage(JSON.parse(frame.body));
});
})
$("#sendMessage").click(function (event) {
event.preventDefault();
var message = $('#text').val();
var username="user@gmail.com";// i am lost in this part, i supose this must be the @DestinationVariable("username")
destination = "/app/chat.private."+to;
stomp.send(destination, {}, JSON.stringify({'text': message}));
$('#text').val("");
});
我目前正在使用具有彈簧安全性的 websocket。 如何在stomp.send
方法上設置@DestinationVariable("username")
。 提前致謝。
查看此 Spring WebSocket Chat 示例,其中包含您要查找的內容: https : //github.com/salmar/spring-websocket-chat
目標變量從您發送的有效負載中填充。 在您的情況下,您必須像這樣包含它
stomp.send(destination, {}, JSON.stringify({'text': message, 'username' : 'User1'}));
另一項觀察是您似乎沒有設置 UserDestinationPrefix。 您需要為 MessageBrokerRegistry 和 SimpMessagingTemplate 設置它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.