【问题标题】:How to Create Spring WebSocket Application With HTML5 WebSocket API?如何使用 HTML5 WebSocket API 创建 Spring WebSocket 应用程序?
【发布时间】:2016-09-18 17:30:14
【问题描述】:

Spring WebSocket 的最新版本适用于 SockJSStompJS 库。 但我不喜欢在我的应用程序中使用主题。那么如何使用HTML5 WebSocket API 创建 Spring WebSocket 应用程序并将我们的应用程序与 Spring Security 集成?

【问题讨论】:

    标签: spring spring-mvc spring-boot spring-websocket


    【解决方案1】:

    我找不到任何关于如何在没有 sockjs 的情况下配置 spring websocket 的好例子,但我在 spring 文档站点中找到了一些有用的 documentation,我喜欢分享。 那么,如何使用 HTML5 WebSocket API 创建 Spring WebSocket 应用程序?

    首先:创建一个扩展 TextWebSocketHandlerBinaryWebSocketHandler并注解它带有 @Component 注释和 Override 其适当的方法。这个 Class 的工作方式类似于控制器中的处理程序方法。

    @Component
    public class SimpleWebSocketHandler extends TextWebSocketHandler {
        @Override
        protected void handleTextMessage(WebSocketSession session, 
                TextMessage message) throws Exception {
            // Sends back response to client.
            session.sendMessage(new TextMessage("Connection is all right."));
        }
    }
    

    第二:创建一个配置类实现WebSocketConfigurer并用@Configuration注解@EnableWebSocket 注释和重写 其适当的方法。这个Class 使用我们已经创建的Handler Class

    @Configuration
    @EnableWebSocket
    public class WebSocketConfigurations implements WebSocketConfigurer {
        @Autowired
        private SimpleWebSocketHandler simpleWebSocketHandler;
    
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            // Regsiters a handler for related endpoint.
            registry.addHandler(simpleWebSocketHandler, "/chat");
        }
    }
    

    第三:将您的所有 WebSokcet 端点添加到您的 Spring 安全配置

    httpSecurity.authorizeRequests()
        .antMatchers("/chat").permitAll();
    

    第四:我们用适当的URL创建一个新的javascript WebSocket对象

    // Create WebSocket Object.
    var ws = new WebSocket("ws://localhost:8080/chat");
    
    // Runs when connecion is estabilished.
    ws.onopen = function () {
        // Sends request to server with string value.
        ws.send("webSocket");
    };
    
    // Runs when response is ready.
    // Use event to get response value.
    ws.onmessage = function (event) {
    
    };
    

    注意:WebSocket URL 格式:ws://domain:port/endpoint

    【讨论】:

    • 谢谢,但我只能在registry.addHandler(simpleWebSocketHandler, "/chat").setAllowedOrigins("*"); 之后使用spring websocket否则我会收到 302 或 403 错误。在我的情况下,Spring 安全配置并没有真正的帮助。
    猜你喜欢
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 2015-11-24
    • 2018-11-24
    • 1970-01-01
    相关资源
    最近更新 更多