| 
         此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.1.10!  | 
    
| 
         此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.1.10!  | 
    
Spring Framework 提供了一个 WebSocket API,您可以使用它来编写客户端和 处理 WebSocket 消息的服务器端应用程序。
WebSocketHandler
创建 WebSocket 服务器就像实现或更多一样简单
可能,扩展 或 .以下
示例使用:WebSocketHandlerTextWebSocketHandlerBinaryWebSocketHandlerTextWebSocketHandler
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.TextMessage;
public class MyHandler extends TextWebSocketHandler {
	@Override
	public void handleTextMessage(WebSocketSession session, TextMessage message) {
		// ...
	}
}
有专用的 WebSocket Java 配置和 XML 命名空间支持,用于映射前面的内容 特定 URL 的 WebSocket 处理程序,如以下示例所示:
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(myHandler(), "/myHandler");
	}
	@Bean
	public WebSocketHandler myHandler() {
		return new MyHandler();
	}
}
以下示例显示了与上述示例等效的 XML 配置:
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/websocket
		https://www.springframework.org/schema/websocket/spring-websocket.xsd">
	<websocket:handlers>
		<websocket:mapping path="/myHandler" handler="myHandler"/>
	</websocket:handlers>
	<bean id="myHandler" class="org.springframework.samples.MyHandler"/>
</beans>
前面的示例用于 Spring MVC 应用程序,应包括在内
在 DispatcherServlet 的配置中。然而,Spring的
WebSocket 支持不依赖于 Spring MVC。相对简单
在 WebSocketHttpRequestHandler 的帮助下将 a 集成到其他 HTTP 服务环境中。WebSocketHandler
当直接使用和间接使用 API 时,例如通过 STOMP 消息传递,应用程序必须同步消息的发送
因为底层标准 WebSocket 会话 (JSR-356) 不允许并发
发送。一种选择是用 ConcurrentWebSocketSessionDecorator 包装。WebSocketHandlerWebSocketSession
WebSocket 握手
自定义初始 HTTP WebSocket 握手请求的最简单方法是通过
a ,它公开了“握手之前”和“握手之后”的方法。
您可以使用此类拦截器来排除握手或创建任何属性
可用于 .下面的示例使用内置侦听器
要将 HTTP 会话属性传递给 WebSocket 会话,请执行以下操作:HandshakeInterceptorWebSocketSession
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(new MyHandler(), "/myHandler")
			.addInterceptors(new HttpSessionHandshakeInterceptor());
	}
}
以下示例显示了与上述示例等效的 XML 配置:
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/websocket
		https://www.springframework.org/schema/websocket/spring-websocket.xsd">
	<websocket:handlers>
		<websocket:mapping path="/myHandler" handler="myHandler"/>
		<websocket:handshake-interceptors>
			<bean class="org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor"/>
		</websocket:handshake-interceptors>
	</websocket:handlers>
	<bean id="myHandler" class="org.springframework.samples.MyHandler"/>
</beans>
一个更高级的选项是扩展执行
WebSocket 握手的步骤,包括验证客户端源,
就子协议进行谈判,以及其他细节。应用程序可能还需要使用它
选项,如果它需要配置自定义以便
适应尚不支持的 WebSocket 服务器引擎和版本
(有关此主题的更多信息,请参阅部署)。
Java 配置和 XML 命名空间都使得配置自定义 .DefaultHandshakeHandlerRequestUpgradeStrategyHandshakeHandler
Spring 提供了一个可用于修饰的基类
a 具有其他行为。日志记录和异常处理
默认情况下,在使用 WebSocket Java 配置时提供和添加实现
或 XML 命名空间。所有未捕获的渔获物
任何方法产生的异常并关闭 WebSocket
会话状态为 ,表示服务器错误。WebSocketHandlerDecoratorWebSocketHandlerExceptionWebSocketHandlerDecoratorWebSocketHandler1011 | 
Spring 提供了一个可用于修饰的基类
a 具有其他行为。日志记录和异常处理
默认情况下,在使用 WebSocket Java 配置时提供和添加实现
或 XML 命名空间。所有未捕获的渔获物
任何方法产生的异常并关闭 WebSocket
会话状态为 ,表示服务器错误。WebSocketHandlerDecoratorWebSocketHandlerExceptionWebSocketHandlerDecoratorWebSocketHandler1011 | 
部署
Spring WebSocket API 很容易集成到 Spring MVC 应用程序中,其中
同时提供 HTTP WebSocket 握手和其他服务
HTTP 请求。它也很容易集成到其他 HTTP 处理场景中
通过调用 .这既方便又容易
理解。但是,对于 JSR-356 运行时,需要注意特殊事项。DispatcherServletWebSocketHttpRequestHandler
Jakarta WebSocket API (JSR-356) 提供了两种部署机制。第一个
在启动时涉及 Servlet 容器类路径扫描(Servlet 3 功能部件)。
另一个是在 Servlet 容器初始化时使用的注册 API。
这两种机制都不能使用单个“前控制器”
用于所有 HTTP 处理 — 包括 WebSocket 握手和所有其他 HTTP
请求 — 例如 Spring MVC 的 .DispatcherServlet
这是 JSR-356 的一个重大限制,Spring 的 WebSocket 支持解决了这个问题
特定于服务器的实现,即使在 JSR-356 运行时中运行时也是如此。
目前,Tomcat、Jetty、GlassFish、WebLogic、WebSphere 和 Undertow 都存在这样的策略
(和 WildFly)。从 Jakarta WebSocket 2.1 开始,可以使用标准请求升级策略
Spring 在基于 Jakarta EE 10 的 Web 容器(如 Tomcat 10.1 和 Jetty 12)上选择。RequestUpgradeStrategy
第二个考虑因素是,应使用支持 JSR-356 的 Servlet 容器
执行可能会减慢应用程序速度的 (SCI) 扫描
启动 - 在某些情况下,戏剧性。如果在
升级到支持 JSR-356 的 Servlet 容器版本,它应该
可以选择性地启用或禁用 Web 片段(和 SCI 扫描)
通过使用 中的元素,如以下示例所示:ServletContainerInitializer<absolute-ordering />web.xml
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
		https://jakarta.ee/xml/ns/jakartaee
		https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
	version="5.0">
	<absolute-ordering/>
</web-app>
然后,您可以有选择地按名称启用 Web 片段,例如 Spring 自己的 Web 片段,它为 Servlet 3 提供支持
Java 初始化 API。以下示例演示如何执行此操作:SpringServletContainerInitializer
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
		https://jakarta.ee/xml/ns/jakartaee
		https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
	version="5.0">
	<absolute-ordering>
		<name>spring_web</name>
	</absolute-ordering>
</web-app>
配置服务器
您可以配置底层 WebSocket 服务器,例如输入消息缓冲区大小、 空闲超时等。
对于 Jakarta WebSocket 服务器,您可以将
Java 配置。例如:ServletServerContainerFactoryBean
@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
    ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
    container.setMaxTextMessageBufferSize(8192);
    container.setMaxBinaryMessageBufferSize(8192);
    return container;
}
或者到您的 XML 配置:
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/websocket
		https://www.springframework.org/schema/websocket/spring-websocket.xsd">
	<bean class="org.springframework...ServletServerContainerFactoryBean">
		<property name="maxTextMessageBufferSize" value="8192"/>
		<property name="maxBinaryMessageBufferSize" value="8192"/>
	</bean>
</beans>
对于客户端 Jakarta WebSocket 配置,请使用
ContainerProvider.getWebSocketContainer() 在 Java 配置或 XML 中。WebSocketContainerFactoryBean | 
对于 Jetty,您可以提供回调来配置 WebSocket 服务器:Consumer
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(echoWebSocketHandler(), "/echo").setHandshakeHandler(handshakeHandler());
	}
	@Bean
	public DefaultHandshakeHandler handshakeHandler() {
		JettyRequestUpgradeStrategy strategy = new JettyRequestUpgradeStrategy();
		strategy.addWebSocketConfigurer(configurable -> {
				policy.setInputBufferSize(8192);
				policy.setIdleTimeout(600000);
		});
		return new DefaultHandshakeHandler(strategy);
	}
}
| 在 WebSocket 上使用 STOMP 时,还需要配置 STOMP WebSocket 传输属性。 | 
对于客户端 Jakarta WebSocket 配置,请使用
ContainerProvider.getWebSocketContainer() 在 Java 配置或 XML 中。WebSocketContainerFactoryBean | 
| 在 WebSocket 上使用 STOMP 时,还需要配置 STOMP WebSocket 传输属性。 | 
允许的源
从 Spring Framework 4.1.5 开始,WebSocket 和 SockJS 的默认行为是接受
仅限同源请求。也可以允许所有或指定的源列表。
此检查主要针对浏览器客户端设计。没有什么能阻止其他类型
的客户端修改标头值(有关详细信息,请参阅 RFC 6454:Web 源概念)。Origin
三种可能的行为是:
- 
只允许同源请求(默认):在这种模式下,当 SockJS 开启时, Iframe HTTP 响应标头设置为 ,JSONP 传输被禁用,因为它不允许检查请求的来源。 因此,启用此模式时不支持 IE6 和 IE7。
X-Frame-OptionsSAMEORIGIN - 
允许指定的源列表:每个允许的源必须以 或 开头。在此模式下,启用 SockJS 时,IFrame 传输将被禁用。 因此,当 模式已启用。
http://https:// - 
允许所有源:要启用此模式,应提供作为允许的源 价值。在此模式下,所有传输都可用。
* 
您可以配置 WebSocket 和 SockJS 允许的源,如以下示例所示:
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(myHandler(), "/myHandler").setAllowedOrigins("https://mydomain.com");
	}
	@Bean
	public WebSocketHandler myHandler() {
		return new MyHandler();
	}
}
以下示例显示了与上述示例等效的 XML 配置:
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/websocket
		https://www.springframework.org/schema/websocket/spring-websocket.xsd">
	<websocket:handlers allowed-origins="https://mydomain.com">
		<websocket:mapping path="/myHandler" handler="myHandler" />
	</websocket:handlers>
	<bean id="myHandler" class="org.springframework.samples.MyHandler"/>
</beans>