gpt4 book ai didi

java - 私有(private)消息 spring websocket

转载 作者:太空宇宙 更新时间:2023-11-04 11:17:23 25 4
gpt4 key购买 nike

我正在学习 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");
}
}

Controller

@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 和 spring security。如何设置 @DestinationVariable("username")stomp.send方法。提前致谢。

最佳答案

查看这个 Spring WebSocket 聊天示例,其中包含您正在寻找的内容:https://github.com/salmar/spring-websocket-chat

关于java - 私有(private)消息 spring websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45308500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com