【问题标题】:Subscribe not working Spring SockJs Stomp订阅不工作 Spring SockJs Stomp
【发布时间】:2017-01-17 11:58:45
【问题描述】:

我想使用 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

【问题讨论】:

    标签: spring websocket stomp sockjs subscribe


    【解决方案1】:

    有一个问题相关: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");
    

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

    【讨论】:

    • 请查看您的浏览器控制台 (f12) 并粘贴整个日志。还可以考虑将 .setAllowedOrigins("*") 放在您的注册表对象上,以解决可能的 cors 问题。
    • 我试试你的建议,我看到并运行你的代码!当我运行您的代码时,一切正常!但是当我运行我的代码时:messagingTemplate.convertAndSend("/topic/notification","test");它抛出一个 NullPointerException 因为messagingTemplate 是空的! =(我用@Autowired声明它,我不知道为什么它这么说我......
    • 您是否使用自定义@ComponentScan?如果是,请确保控制器的包装已盖好。 @ComponentScan(basePackages = "com.x.y.*") 在您的主要 Spring Boot 类中。并查看您的文件夹结构。
    猜你喜欢
    • 2016-11-09
    • 1970-01-01
    • 2020-10-16
    • 2019-12-03
    • 2015-01-26
    • 2017-06-05
    • 1970-01-01
    • 2016-12-29
    • 2017-05-27
    相关资源
    最近更新 更多