如何在现有spring应用程序中创建websocket端点

时间:2018-03-10 11:56:54

标签: spring spring-websocket

我正在尝试在现有的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);
    }   

}

1 个答案:

答案 0 :(得分:0)

我可以为您提供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配置的信息。我自己没有测试过。