我希望使用WebSocket从服务器向客户端发送一些内容。
以下是我的代码:
---- 服务器上WebSocket配置 ----
@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
@Component
@Slf4j
public class MenuItemController{
@SendTo("/topic/notification")
public String sendToMenuItems(MenuItemDto menuItem) {
return menuItem.getMenuItemName();
}
}
----- 客户端 ----
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();
我使用context.backend,因为我使用webpack,所以websocket通过后台服务器连接。它可以用于连接和订阅似乎也正常,但是当我从服务器向客户端发送消息时,警报不会出现,并且在控制台中没有websocket传入的消息。我的问题是什么?希望有人能帮助我.. = D
.setAllowedOrigins("*")
以解决可能存在的CORS问题。 - Cleto GadelhamessagingTemplate.convertAndSend("/topic/notification","test");
它会抛出一个NullPointerException,因为messagingTemplate为空! =( 我用@Autowired声明了它,不知道为什么会这样告诉我.. - Catechacha