配置 WebSocket
配置有两种方式:注解和 xml 。其作用就是将 WebSocket 处理器添加到注册中心。
[url=][/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 { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "/myHandler"); } @Bean public WebSocketHandler myHandler() { return new MyHandler(); }}[url=][/url]
[url=][/url]
<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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/websocket http://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>[url=][/url]
更多配置细节可以参考:
javax.websocket如果不想使用 Spring 框架的 WebSocket API,你也可以选择基本的 javax.websocket。
首先,需要引入 API jar 包。
[url=][/url]
<!-- To write basic javax.websocket against --><dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.0</version></dependency>[url=][/url]
如果使用嵌入式 jetty,你还需要引入它的实现包:
[url=][/url]
<!-- To run javax.websocket in embedded server --><dependency> <groupId>org.eclipse.jetty.websocket</groupId> <artifactId>javax-websocket-server-impl</artifactId> <version>${jetty-version}</version></dependency><!-- To run javax.websocket client --><dependency> <groupId>org.eclipse.jetty.websocket</groupId> <artifactId>javax-websocket-client-impl</artifactId> <version>${jetty-version}</version></dependency> |