spring-websocket

写的不完整。待补充

spring4之后开始支持websocket了,maven坐标:

1
2
3
4
5
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${org.springframework-version}</version>
</dependency>

配置

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>Spring WebSocket</display-name>
<!-- spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring-context.xml
</param-value>
</context-param>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
  • javaee的web标准必须是web-app_3_0及以上
  • servlet 必须配置 true

spring.xml

1
<context:component-scan base-package="com.xxx.websocket.config" />

sockjs

心跳检测

sockjs可以进行心跳检测,默认心跳间隔是25秒,可以通过setHeartbeatTime方法重设心跳间隔

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(echoHandler(), "/echoWebSocket").addInterceptors(new WebSocketHandshakeInterceptor());
registry.addHandler(echoHandler(), "/sockjs/echoWebSocket").addInterceptors(new WebSocketHandshakeInterceptor()).withSockJS().setHeartbeatTime(1000);
}
@Bean
public WebSocketHandler echoHandler() {
return new EchoHandler();
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}