Reputation: 245
I'm working on WebSocket chat. I've made simple one that sends every message to everyone. But I'm trying to make something like private messaging and I really don't know how to do that. I've tried different options but I'don't understand how to make it work.
Here's my code:
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());
}
}
And my js function to connect and sending message:
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())
}));
}
How to make private message work? Could somebody explain me how it should work?
Cheers Andrew!
Upvotes: 3
Views: 1787
Reputation: 5283
We can make use of SimpMessagingTemplate to send the message to appropriate destination queues
@Autowired
private SimpMessagingTemplate template;
@MessageMapping("/hello")
public void greeting(Message message) throws Exception {
this.template.convertAndSend("/topic/"+message.getFrom_user_id(),message);
}
Accordingly define the subscription to the topics in the client side
Upvotes: 2