Im writing back front java code spring 2.2.5. The front is connected to the back via a websocket. I want to send notifications to the client without request sent by client only connection and subscrition events are received by the server. I tried some solotion based on SimpMessagingTemplate but when i'm trying to send back to the client using this interface (without request) the data is null pointer.
Controller code :
private SimpMessagingTemplate messagingTemplate;
@Autowired
public void WebSocketController(SimpMessagingTemplate messagingTemplate) {
this.messagingTemplate = messagingTemplate;
}
@RequestMapping(value = "/post/message", method = RequestMethod.POST)
public void PostMessage(@PathVariable String message) {
this.messagingTemplate.convertAndSend("/topic/myDest", message);
}
With the following config code i intercept connect and subscribe events, is there a way to save client parameter in order to send back notifications to it.
@Override
public void configureClientInboundChannel(ChannelRegistration registration){
registration.interceptors(new ChannelInterceptor() {
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if(StompCommand.CONNECT.equals(accessor.getCommand())){
String sessionId = accessor.getSessionId();
System.out.println("Connect " sessionId);
} else if(StompCommand.SUBSCRIBE.equals(accessor.getCommand())){
System.out.println("Subscribe ");
} else if(StompCommand.SEND.equals(accessor.getCommand())){
System.out.println("Send message " );
} else if(StompCommand.DISCONNECT.equals(accessor.getCommand())){
System.out.println("Exit ");
} else {
}
return message;
}
});
}
CodePudding user response:
I finally find the solution: In my previous PreSend interceptor, i can save all subscribed clients :
xxxx.Channels.add(channel);
In xxx class : Channels is defined as :
public final ArrayList<MessageChannel> Channels = new ArrayList<MessageChannel>();
In Post function i created a SimpMessagingTemplate instance for each channel :
for (int i = 0; i < Channels.size(); i ) {
MessageChannel channel = Channels.get(i);
SimpMessagingTemplate messagingTemplate = new SimpMessagingTemplate(channel);
messagingTemplate.convertAndSend("/topic/myDest", data.toString().getBytes());
}
And the message is correctly sent.