创建 WebSocket 服务器 就像实现 WebSocketHandler 一样简单,或者更可能的是扩展 TextWebSocketHandler 或 BinaryWebSocketHandler。下面的例子使用了 TextWebSocketHandler:
import org.springframework.web.socket.WebSocketHandler;import org.springframework.web.socket.WebSocketSession;import org.springframework.web.socket.TextMessage;public class MyHandler extends TextWebSocketHandler {@Overridepublic void handleTextMessage(WebSocketSession session, TextMessage message) {// ...}}
有专门的 WebSocket Java 配置和 XML 命名空间支持,用于将前面的 WebSocket 处理程序映射到一个特定的 URL,如下例所示:
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@EnableWebSocketpublic class WebSocketConfig implements WebSocketConfigurer {@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {registry.addHandler(myHandler(), "/myHandler");}@Beanpublic 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/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/websockethttps://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 的帮助下,将 WebSocketHandler 集成到其他 HTTP 服务环境中是比较简单的。
当直接或间接使用 WebSocketHandler API 时,例如通过 STOMP 消息传递,应用程序必须同步发送消息,因为底层标准 WebSocket 会话(JSR-356)不允许并发发送。一种选择是用 ConcurrentWebSocketSessionDecorator 来包装 WebSocketSession。
