订阅不起作用 Spring SockJs Stomp

3

我希望使用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

1个回答

4

有一个相关问题:https://github.com/spring-guides/gs-messaging-stomp-websocket/issues/10

使用

stompClient.connect({}, function(frame) {

代替
stompClient.connect("","",function (frame) {

编辑: 如果您想使用Rest Controller,请使用SimpMessagingTemplate发送消息。

@Autowired
private SimpMessagingTemplate messagingTemplate;

而你的方法将会调用

messagingTemplate.convertAndSend("/topic/notification", "test");

如果没有,请确保在sendToMenuItems上注释@MessageMapping(value = "/sentToMenu"),并且您有一个适当的stomp客户端发送消息:stompClient.send("/sentToMenu", {}, 'teste');

请查看您的浏览器控制台(F12),并粘贴整个日志。同时,考虑在您的注册表对象上添加.setAllowedOrigins("*")以解决可能存在的CORS问题。 - Cleto Gadelha
我尝试了你的建议并运行了你的代码!当我运行你的代码时,一切都很顺利!但是当我使用以下代码运行我的代码时: messagingTemplate.convertAndSend("/topic/notification","test");它会抛出一个NullPointerException,因为messagingTemplate为空! =( 我用@Autowired声明了它,不知道为什么会这样告诉我.. - Catechacha
你是否使用了自定义的@ComponentScan?如果是,请确保控制器所在的包被覆盖。在你的Spring Boot主类中添加@ComponentScan(basePackages = "com.x.y.*")。同时检查你的文件夹结构。 - Cleto Gadelha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接