【问题标题】:How to create a websocket endpoint in an existing spring application如何在现有的 Spring 应用程序中创建 websocket 端点
【发布时间】:2018-03-10 11:56:53
【问题描述】:

我正在尝试在现有的 spring 应用程序中提供一个新的 websocket 端点。

我正在关注https://docs.spring.io/spring/docs/4.3.2.RELEASE/spring-framework-reference/html/websocket.html#websocket-server-handler 的文档。但根据文档,我应该配置 DispatcherServlet 或使用 WebSocketHttpRequestHandler

如何在不更改 web.xml 配置文件的情况下使 websocket 端点可用?

这是我尝试过的,但不起作用(找不到客户端错误 404)。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ws="http://jax-ws.dev.java.net/spring/core" xmlns:wss="http://jax-ws.dev.java.net/spring/servlet"
  xmlns:websocket="http://www.springframework.org/schema/websocket"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
                           http://jax-ws.dev.java.net/spring/core http://jax-ws.dev.java.net/spring/core.xsd
                           http://jax-ws.dev.java.net/spring/servlet http://jax-ws.dev.java.net/spring/servlet.xsd
                           http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd">

    <websocket:handlers  allowed-origins="*">
        <websocket:mapping path="/ws" handler="websocketService"/>
        <websocket:handshake-interceptors>
            <bean class="org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor"/>
        </websocket:handshake-interceptors>
    </websocket:handlers>    

    <bean id="websocketService" class="com.krios.SocketHandler"/>

</beans>

类文件:

public class SocketHandler extends TextWebSocketHandler {

    List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message)
            throws InterruptedException, IOException {

        for(WebSocketSession webSocketSession : sessions) {
            Map value = new Gson().fromJson(message.getPayload(), Map.class);
            webSocketSession.sendMessage(new TextMessage("Hello " + value.get("name") + " !"));
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //the messages will be broadcasted to all users.
        sessions.add(session);
    }   

}

【问题讨论】:

    标签: spring spring-websocket


    【解决方案1】:

    我可以为您提供 java 配置(您可以自己将其更改为 xml 或将其用作 java 类并从 xml 扫描)

    @Configuration
    @EnableWebSocket
    public class WebSocketConfig implements WebSocketConfigurer {
        @Bean
        public MessagingWebSocketHandler webSocketHandler() {
            //handler of your websocket. should be a class implementing WebSocketHandler.
            //You could also extend AbstractWebSocketHandler or TextWebSocketHandler and override methods
            return new MessagingWebSocketHandler(); 
        }
    
        @Bean
        public WebSocketContainerFactoryBean createWebSocketContainer() {
            WebSocketContainerFactoryBean container = new WebSocketContainerFactoryBean();
            container.setMaxTextMessageBufferSize(StaticConfig.MAXIMUM_WS_TEXT_BUFFER_SIZE);
            container.setMaxBinaryMessageBufferSize(StaticConfig.MAXIMUM_WS_BINARY_BUFFER_SIZE);
            container.setMaxSessionIdleTimeout(StaticConfig.MAXIMUM_WS_SESSION_IDLE_TIMEOUT);
            container.setAsyncSendTimeout(StaticConfig.MAXIMUM_WS_ASYNC_SEND_TIMEOUT);
            return container;
        }
    
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
            webSocketHandlerRegistry.addHandler(webSocketHandler(), "/message").setAllowedOrigins("*"); // you could also get handler from context 
        }
    
    }
    

    希望有帮助。

    更新

    我自己不使用基于 xml 的配置。但最简单的方法是添加此 java 代码,然后从 xml 扫描它。例如,通过将此行添加到您的 spring servlet 配置 xml 中,您可以扫描您的配置包或整个项目包。

    <context:component-scan base-package="com.my.company.config" />
    

    那么你的WebSocketConfig类必须在com.my.company.config

    Websocket 支持和配置的文档是here。在创建和配置 WebSocketHandler 部分,您可以阅读有关 xml 配置的信息。我自己没有测试过。

    【讨论】:

    • 嗨@SepehrGH,我对Spring没有太多经验。你介意在你的答案中包含相应的 xml 配置吗?这将非常有用。
    • 我更新了我的答案。我通常不使用 xml 配置,所以我无法为您提供我自己测试过的代码。但我知道组件扫描可以帮助您扫描那些配置文件。我还添加了 Websocket 支持文档的链接。那里有一堆有效的代码可供您使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 2017-08-21
    • 2018-12-20
    • 2018-10-22
    • 2021-03-28
    相关资源
    最近更新 更多