使用Spring的Websocket服务器/客户端

时间:2019-03-07 15:09:53

标签: java spring-boot websocket

我是WebSockets的新手,正在尝试创建一个基于Spring的Websocket Server以及与之通信的Java客户端。但是,我在实际连接方面遇到了问题。我以为它与我的WebSocketConfig.java有关,尽管我对Websockets如何工作以正确地连接起来不甚了解。在线上有很多指南都显示了示例代码,但并没有很多解释。实际发生了什么,以及实际如何工作。

我也对websocket似乎可以实现的许多方式感到困惑...最终,我希望对此进行设置,以使服务器能够与各个客户端进行通信。我在正确的道路上吗?

连接时出错:

Caused by: org.glassfish.tyrus.core.HandshakeException: Response code was not 101: 404.

客户代码:

public static void main(String[] args) throws InterruptedException {
    LOGGER.info("Running Main.");

    WebSocketClient client = new StandardWebSocketClient(); //provided by Tyrus

    WebSocketStompClient stompClient = new WebSocketStompClient(client);
    stompClient.setMessageConverter(new MappingJackson2MessageConverter());

    StompSessionHandler sessionHandler = new MyStompSessionHandler();
    stompClient.connect("ws://localhost:8080/websocket-api/chat/foo", sessionHandler);

    Thread.sleep(10_000);
}

服务器代码:(主要基于Spring的示例WebSocket教程)

ChatController.java

@Controller
public class ChatController {

    @MessageMapping("/websocket-api/chat/{topic}")
    @SendTo("/websocket-api/topic/messages")
    public OutputMessage send(
            @DestinationVariable("topic") String topic,
            Message message
    ) throws Exception {
        return new OutputMessage(message.getFrom(), message.getText(), topic);
    }
}

WebSocketConfig.java

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Value("/websocket-api") //to be put into configuration eventually
    private String baseWebsocketApi;

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker(baseWebsocketApi + "/topic");
        config.setApplicationDestinationPrefixes(baseWebsocketApi + "/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint(baseWebsocketApi + "/chat").setAllowedOrigins("*").withSockJS();
    }
}

0 个答案:

没有答案