我正在进行WebSocket聊天。我做了一个简单的发送给每个人的每条消息。但我试图制作私人消息,我真的不知道如何做到这一点。我尝试了不同的选择,但我不了解如何使其发挥作用。
这是我的代码:
WebSocketConfig.java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic/", "/queue/", "/user/");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket").withSockJS();
}
}
GreetingController.java
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(Message message) throws Exception {
return new Greeting(message.getFrom_user_id(), message.getMessage(), message.getTo_user_id());
}
}
我的js用于连接和发送消息:
function connect() {
var socket = new SockJS('/gs-guide-websocket');
stompClient = Stomp.over(socket);
var theUserId = 1;
stompClient.connect({user:theUserId}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
//stompClient.subscribe('/topic/greetings', function (greeting) {
stompClient.subscribe('/topic/greetings', function (greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function sendName() {
stompClient.send("/app/hello", {}, JSON.stringify(
{
'from_user_id': parseInt($("#from_user_id").val()),
'message': $("#message").val(),
'to_user_id': parseInt($("#to_user_id").val())
}));
}
如何使私信有效?有人可以解释一下它应该如何运作吗?
干杯安德鲁!
答案 0 :(得分:1)
我们可以使用 SimpMessagingTemplate 将邮件发送到适当的目标队列
@Autowired
private SimpMessagingTemplate template;
@MessageMapping("/hello")
public void greeting(Message message) throws Exception {
this.template.convertAndSend("/topic/"+message.getFrom_user_id(),message);
}
相应地定义对客户端主题的订阅