我没有收到 WebSocket 消息 (SimpMessagingTemplate)

I am not receiving WebSocket messages (SimpMessagingTemplate)

我的 WS 无法正常工作。我写了这个测试,当我使用 simpMessagingTemplate 时它仍然失败,但是当我使用 stompSession.send 时它有效。谁能帮我看看我哪里出错了?

问题不在测试中可能,我无法使 simpMessagingTemplate 在任何服务中工作。

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(MockitoExtension.class)
public class WebSocketSpec {
    @LocalServerPort
    private Integer port;
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    private WebSocketStompClient webSocketStompClient;


@BeforeEach
public void initialize(){
    webSocketStompClient = new WebSocketStompClient(new SockJsClient(List.of(new WebSocketTransport(new StandardWebSocketClient()))));
}

@Test @DisplayName("test subscription to /topic/plcs/connection-status")
void testSubscriptionToPlcConnectionEndpoint() throws Exception{
    CountDownLatch latch = new CountDownLatch(1);

    webSocketStompClient.setMessageConverter(new MappingJackson2MessageConverter());

    StompSession stompSession = webSocketStompClient.connect("ws://localhost:" + port+"/api/ws", new StompSessionHandlerAdapter() {
    }).get(1, TimeUnit.SECONDS);

    stompSession.subscribe("/topic/plcs/connection-status", new StompFrameHandler() {
        @Override
        public Type getPayloadType(StompHeaders stompHeaders) {
            return String.class;
        }

        @Override
        public void handleFrame(StompHeaders stompHeaders, Object o) {
            latch.countDown();
            System.out.println("RECEIVED: "+o);
        }
    });

    //stompSession.send("/topic/plcs/connection-status", "SENT FROM TEST!!!");
    simpMessagingTemplate.convertAndSend("/topic/plcs/connection-status", "SENT FROM TEST!!!");

    if (!latch.await(5, TimeUnit.SECONDS)){
        fail("Message not received");
    }
}
}

我的 WS 配置如下所示:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/queue", "/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS();
    }
}

所以,其实有两个问题...

  1. 首先是你用错了messageConvertornew MappingJackson2MessageConverter()而不是new StringMessageConverter()
  2. simpMessagingTemplate.convertAndSend("/topic/plcs/connection-status", "SENT FROM TEST!!!"); 在客户端订阅之前被解雇,我刚刚尝试用 Thread.sleep(500); 在它之前放置一些延迟并且成功了。