I want to use websocket to send from server to client something.. Here's my code:
---- Websocket configuration on server ----
@Configuration
@EnableWebSocketMessageBroker
@Slf4j
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/myWebSocketEndPoint")
.withSockJS();
}
}
---- Controller---
@Controller
@Component
@Slf4j
public class MenuItemController{
@SendTo("/topic/notification")
public String sendToMenuItems(MenuItemDto menuItem) {
return menuItem.getMenuItemName();
}
}
----- Client ----
var SockJS = require('sockjs-client');
var Stomp = require('stompjs');
let connectWebSocket = () => {
socket = new SockJS(context.backend + '/myWebSocketEndPoint');
stompClient = Stomp.over(socket);
stompClient.connect({},function (frame) {
console.log(frame);
stompClient.subscribe('/topic/notification', function(menuItem){
alert(menuItem);
});
});
}
connectWebSocket();
I use context.backend because i use webpack, so websocket connect over the backend server. It works for connect and also subscribe seems working, but when i send something from server to client, the alert doesn't appear and in console there are no message incoming by websocket. What's my problem? I hope someone can help me.. =D
There is a issue related: https://github.com/spring-guides/gs-messaging-stomp-websocket/issues/10
use
stompClient.connect({}, function(frame) {
instead of
stompClient.connect("","",function (frame) {
Edit: If you are wondering to use Rest Controller please use SimpMessagingTemplate to send your messages.
@Autowired
private SimpMessagingTemplate messagingTemplate;
and your method will call
messagingTemplate.convertAndSend("/topic/notification", "test");
If not, be sure to annotate your sendToMenuItems with @MessageMapping(value = "/sentToMenu")
and you have a proper stomp client sending a message: stompClient.send("/sentToMenu", {}, 'teste');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.