Spring+Websocket实现消息的推送
- - Java - 编程语言 - ITeye博客本文主要有三个步骤 1、用户登录后建立websocket连接,默认选择websocket连接,如果浏览器不支持,则使用sockjs进行模拟连接 2、建立连接后,服务端返回该用户的未读消息 3、服务端进行相关操作后,推送给某一个用户或者所有用户新消息 相关环境 Spring4.0.6(要选择4.0+),tomcat7.0.55.
@Configuration @EnableWebMvc @EnableWebSocket public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(systemWebSocketHandler(),"/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor()); registry.addHandler(systemWebSocketHandler(), "/sockjs/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor()) .withSockJS(); } @Bean public WebSocketHandler systemWebSocketHandler(){ return new SystemWebSocketHandler(); } }
<context:component-scan base-package="com.ldl.origami.websocket" />
registry.addHandler(systemWebSocketHandler(),"/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor())
registry.addHandler(systemWebSocketHandler(), "/sockjs/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor()) .withSockJS(); }
public class SystemWebSocketHandler implements WebSocketHandler { private static final Logger logger; private static final ArrayList<WebSocketSession> users; static { users = new ArrayList<>(); logger = LoggerFactory.getLogger(SystemWebSocketHandler.class); } @Autowired private WebSocketService webSocketService; @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { logger.debug("connect to the websocket success......"); users.add(session); String userName = (String) session.getAttributes().get(Constants.WEBSOCKET_USERNAME); if(userName!= null){ //查询未读消息 int count = webSocketService.getUnReadNews((String) session.getAttributes().get(Constants.WEBSOCKET_USERNAME)); session.sendMessage(new TextMessage(count + "")); } } @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { //sendMessageToUsers(); } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { if(session.isOpen()){ session.close(); } logger.debug("websocket connection closed......"); users.remove(session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { logger.debug("websocket connection closed......"); users.remove(session); } @Override public boolean supportsPartialMessages() { return false; } /** * 给所有在线用户发送消息 * * @param message */ public void sendMessageToUsers(TextMessage message) { for (WebSocketSession user : users) { try { if (user.isOpen()) { user.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } } } /** * 给某个用户发送消息 * * @param userName * @param message */ public void sendMessageToUser(String userName, TextMessage message) { for (WebSocketSession user : users) { if (user.getAttributes().get(Constants.WEBSOCKET_USERNAME).equals(userName)) { try { if (user.isOpen()) { user.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } break; } } } }
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor { private static Logger logger = LoggerFactory.getLogger(HandshakeInterceptor.class); @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object > attributes) throws Exception { if (request instanceof ServletServerHttpRequest) { ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request; HttpSession session = servletRequest.getServletRequest().getSession(false); if (session != null) { //使用userName区分WebSocketHandler,以便定向发送消息 String userName = (String) session.getAttribute(Constants.SESSION_USERNAME); attributes.put(Constants.WEBSOCKET_USERNAME,userName); } } return true; } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) { } }
<script type="text/javascript" src="http://localhost:8080/Origami/websocket/sockjs-0.3.min.js"></script> <script> var websocket; if ('WebSocket' in window) { websocket = new WebSocket("ws://localhost:8080/Origami/webSocketServer"); } else if ('MozWebSocket' in window) { websocket = new MozWebSocket("ws://localhost:8080/Origami/webSocketServer"); } else { websocket = new SockJS("http://localhost:8080/Origami/sockjs/webSocketServer"); } websocket.onopen = function (evnt) { }; websocket.onmessage = function (evnt) { $("#msgcount").html("(<font color='red'>"+evnt.data+"</font>)") }; websocket.onerror = function (evnt) { }; websocket.onclose = function (evnt) { } </script>
<script type="text/javascript" src="http://localhost:8080/Origami/websocket/sockjs-0.3.min.js"></script> websocket = new SockJS("http://localhost:8080/Origami/sockjs/webSocketServer");
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd">
version web-app_3_1.xsd
<async-supported>true</async-supported>
<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*:servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet>
<async-supported>true</async-supported>
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.3.3</version> </dependency>
public class AdminController { static Logger logger = LoggerFactory.getLogger(AdminController.class); @Autowired(required = false) private AdminService adminService; @Bean public SystemWebSocketHandler systemWebSocketHandler() { return new SystemWebSocketHandler(); } @RequestMapping("/auditing") @ResponseBody public String auditing(HttpServletRequest request){ //无关代码都省略了 int unReadNewsCount = adminService.getUnReadNews(username); systemWebSocketHandler().sendMessageToUser(username, new TextMessage(unReadNewsCount + "")); return result; } }