我没有收到websocket消息(simpmessagingtemplate)

evrscar2  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(735)

我不能让我的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();
    }
}
h7wcgrx3

h7wcgrx31#

所以,实际上有两个问题。。。
首先是您使用了错误的messageconverter( new MappingJackson2MessageConverter() 而不是 new StringMessageConverter() )
这个 simpMessagingTemplate.convertAndSend("/topic/plcs/connection-status", "SENT FROM TEST!!!"); 在客户端被订阅之前就被解雇了,我只是试着在它之前加上一些延迟 Thread.sleep(500); 而且成功了。

相关问题