spring+websocket的使用
一、spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket-4.1.xsd ">
<!-- @Autowired等注解驱动 -->
<context:annotation-config />
<mvc:annotation-driven/>
<!--一定要扫描指定的项目报-->
<context:component-scan base-package="com.soccermaster.websocket"></context:component-scan>
<context:component-scan base-package="com.soccermaster.service"></context:component-scan>
<context:component-scan base-package="com.soccermaster.dao"></context:component-scan>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/pages/" p:suffix=".jsp">
</bean>
</beans>
二、web.xml配置
注意:必须将对应filter和servlet添加
<async-supported>true</async-supported>
<?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" 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> <welcome-file-list> <welcome-file>testSocket.jsp</welcome-file> </welcome-file-list> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <session-config> <session-timeout>30</session-timeout> </session-config> </web-app>
三、代码
a、websocketconfig
package com.soccermaster.websocket; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import org.springframework.context.annotation.Bean; @Configuration @EnableWebMvc @EnableWebSocket public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer { public WebSocketConfig() { } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(systemWebSocketHandler(), "/websck").addInterceptors(new WebSocketHandshakeInterceptor()); System.out.println("registed!"); registry.addHandler(systemWebSocketHandler(), "/sockjs/websck/info").addInterceptors(new WebSocketHandshakeInterceptor()).withSockJS(); } @Bean public WebSocketHandler systemWebSocketHandler() { //return new InfoSocketEndPoint(); return new SystemWebSocketHandler(); } }
b、WebSocketHandshakeInterceptor
package com.soccermaster.websocket; import java.util.Map; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.stereotype.Component; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; @Component public class WebSocketHandshakeInterceptor extends HttpSessionHandshakeInterceptor { @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { System.out.println("Before Handshake"); return super.beforeHandshake(request, response, wsHandler, attributes); } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) { System.out.println("After Handshake"); super.afterHandshake(request, response, wsHandler, ex); } }
c、SystemWebSocketHandler
package com.soccermaster.websocket; import java.io.IOException; import java.util.ArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession; <!--如下接口是自己的业务接口 根据情况自定义--> import com.soccermaster.service.IMatchService; import com.soccermaster.util.json.JsonConvert; /** * */ @Component public class SystemWebSocketHandler implements WebSocketHandler { @Autowired private IMatchService matchService; private static final Logger logger; private static final ArrayList<WebSocketSession> users; static { users = new ArrayList<WebSocketSession>(); logger = LoggerFactory.getLogger(SystemWebSocketHandler.class); } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { logger.debug("connect to the websocket success......"); System.out.println("connect to the websocket success......"); session.sendMessage(new TextMessage("Server:connected OK!")); users.add(session); } @Override public void handleMessage(WebSocketSession wss, WebSocketMessage<?> wsm) throws Exception { logger.debug("websocket handle message......"); TextMessage returnMessage = new TextMessage(result); wss.sendMessage("服务端返回信息"); //sendMessageToUsers(wss, wsm); } @Override public void handleTransportError(WebSocketSession wss, Throwable thrwbl) throws Exception { if (wss.isOpen()) { wss.close(); } users.remove(wss); logger.debug("websocket connection closed happen error......"); System.out.println("websocket connection closed happen error......"); } @Override public void afterConnectionClosed(WebSocketSession wss, CloseStatus cs) throws Exception { System.out.println("websocket connection closed......"); users.remove(wss); logger.debug("websocket connection closed......"); } @Override public boolean supportsPartialMessages() { return false; } }
四、相关项目jar包 http://pan.baidu.com/s/1sjI9GOt
如上基本完成 spring websocket
环境要求tomcat7及其以上 + jdk 1.7
五、补充 关于浏览器不支持websocket , 通过http请求来模拟注意事宜
需要添加jackson2相关的jar包(见附件)
上一篇: 用Docker 构建RabbitMQ shovel(动态)
下一篇: websocket