简体   繁体   English

Spring 启动 WebSocketStompClient 未收到消息

[英]Spring boot WebSocketStompClient not receiving messages

Currently, I can see that in the test case I am able to successfully connect and send messages to WS server/endpoint.目前,我可以看到在测试用例中我能够成功连接并向 WS 服务器/端点发送消息。 However, I am not receiving any message.但是,我没有收到任何消息。 The completeableFuture object in the test case waits for the message for 10 secs and then times out.测试用例中的completeableFuture object 等待消息10秒然后超时。 I tried to debug as well into the source code wherein I could see that session , destination , subscribers are loaded correctly我也尝试调试源代码,其中我可以看到sessiondestinationsubscribers已正确加载

My WebSocketConfig:我的 WebSocket 配置:

@EnableWebSocketMessageBroker
class WebSocketConfig : WebSocketMessageBrokerConfigurer {

    override fun registerStompEndpoints(registry: StompEndpointRegistry) {
        registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS()
    }

    override fun configureMessageBroker(registry: MessageBrokerRegistry) {
        registry.enableSimpleBroker( "/topic/")
        registry.setApplicationDestinationPrefixes("/api/")
        //registry.setUserDestinationPrefix("/user")
    }

Controller: Controller:

class ChatController(private val chatService: ChatService) {

    @MessageMapping("/user/chat/{channelId}")
    @SendTo("/topic/chat/{channelId}")
    fun chatMessage(@DestinationVariable("channelId") channelId: UUID, chatMessageDTO: ChatMessageDTO): ChatNotification {
        return chatService.submitMessage(chatMessageDTO, channelId)
    }

Service:服务:

 fun establishChatSession(chatChannelDTO: ChatChannelDTO): ChatChannelDTO {
        if (chatChannelDTO.userOne == chatChannelDTO.userTwo) {
            throw InvalidInputDataException("")
        }
        val optionalChatChannel = getExistingChannel(chatChannelDTO)
        return if (optionalChatChannel.isPresent) {
            ChatChannelDTO.fromChatChannel(optionalChatChannel.get())
        } else {
            newChatSession(chatChannelDTO)
        }
    }

Test:测试:

class ChatControllerIT(@Autowired private val chatService: ChatService, @Autowired private val  simpleMessagingTemplate: SimpMessagingTemplate) {

    @Value("\${local.server.port}")
    var port = 0;

    var completableFuture: CompletableFuture<ChatNotification> = CompletableFuture()
    lateinit var webSocketStompClient: WebSocketStompClient

    @BeforeEach
    fun setup() {
        this.webSocketStompClient = WebSocketStompClient(SockJsClient(listOf(WebSocketTransport(StandardWebSocketClient()))))
        webSocketStompClient.messageConverter = MappingJackson2MessageConverter()
    }

    @Test
    fun verifyGreetingIsReceived() {
        val channel = chatService.establishChatSession(ChatChannelDTO(userOne = UUID.randomUUID(), userTwo = UUID.randomUUID()))
        val stompSession = webSocketStompClient.connect("ws://localhost:$port/ws", object : StompSessionHandlerAdapter() {}).get(10, TimeUnit.SECONDS)
        println("subscribing to::::::::::   /topic/chat/${channel.channelId}")

        val message = ChatMessageDTO(message = "Hello", senderId = channel.userOne, senderName = "Pranav", recipientName = "Monika", recipientId = channel.userTwo)
        stompSession.send("/api/user/chat/${channel.channelId}", message)

        stompSession.subscribe("/topic/chat/${channel.channelId}", object: StompFrameHandler{

            override fun getPayloadType(headers: StompHeaders): Type {
                return ChatNotification::class.java
            }

            override fun handleFrame(headers: StompHeaders, @Nullable payload: Any?) {
                completableFuture.complete(payload as ChatNotification)
            }
        })

        val response = completableFuture.get(10, TimeUnit.SECONDS)
        println(response)
    }
}

Any idea on whats going wrong here?关于这里出了什么问题的任何想法?

This code looks correct to me.这段代码对我来说是正确的。 I created example project and it works.我创建了示例项目并且它有效。 Are you sure local.server.port has the correct value.您确定 local.server.port 具有正确的值。 Try this test class.试试这个测试 class。 If it doesn't work, contact me directly and I'll send you example project如果它不起作用,请直接与我联系,我将向您发送示例项目

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ChatControllerIT(@Autowired private val chatService: ChatService) {

    @LocalServerPort
    var port = 0

    var completableFuture: CompletableFuture<ChatNotification> = CompletableFuture()
    lateinit var webSocketStompClient: WebSocketStompClient

    @BeforeEach
    fun setup() {
        this.webSocketStompClient = WebSocketStompClient(SockJsClient(listOf(WebSocketTransport(StandardWebSocketClient()))))
        webSocketStompClient.messageConverter = MappingJackson2MessageConverter()
    }

    @Test
    fun verifyGreetingIsReceived() {
        val channel = chatService.establishChatSession(ChatChannelDTO(userOne = UUID.randomUUID(), userTwo = UUID.randomUUID()))
        val stompSession = webSocketStompClient.connect("ws://localhost:$port/ws", object : StompSessionHandlerAdapter() {}).get(10, TimeUnit.SECONDS)
        println("subscribing to::::::::::   /topic/chat/${channel.channelId}")

        val message = ChatMessageDTO(message = "Hello", senderId = channel.userOne, senderName = "Pranav", recipientName = "Monika", recipientId = channel.userTwo)
        stompSession.send("/api/user/chat/${channel.channelId}", message)

        stompSession.subscribe("/topic/chat/${channel.channelId}", object: StompFrameHandler {

            override fun getPayloadType(headers: StompHeaders): Type {
                return ChatNotification::class.java
            }

            override fun handleFrame(headers: StompHeaders, @Nullable payload: Any?) {
                completableFuture.complete(payload as ChatNotification)
            }
        })

        val response = completableFuture.get(10, TimeUnit.SECONDS)
        println(response)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM