A websocket real-time push example written based on the spring framework, the specific content is as follows
Step 1: Build a springmvc project yourself, it is very simple, available on Baidu online; add the following pom file:
<!-- WebSocket --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</artifactId> <version>4.2.4.RELEASE</version> </dependency>
My spring version is 4.2.4, so websocket is also 4.2.4; it is best to keep the same as the spring version
Step 2: Write a message processor
/** * Project Name:springRabbitMQ * File Name:MyMessageHandler.java * Package Name:com.zsy.websocket * Date: January 31, 2018 at 11:10:03 am * Copyright (c) 2018, zhaoshouyun All Rights Reserved. * */ package com.zsy.websocket; import java.io.IOException; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang3.StringUtils; 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; /** * ClassName: MyMessageHandler * Function: Implement the webscoket interface* date: January 31, 2018 at 11:10:03 am * @author zhaoshouyun * @version * @since JDK 1.7 */ public class MyMessageHandler implements WebSocketHandler { //User key public static final String USER_KEY = "current_user"; /** * userMap:Storing user connection webscoket information* @since JDK 1.7 */ private final static Map<String, WebSocketSession> userMap; static { userMap = new ConcurrentHashMap<String,WebSocketSession>(30); } /** * This method is called when closing the websocket* @see org.springframework.web.socket.WebSocketHandler#afterConnectionClosed(org.springframework.web.socket.WebSocketSession, org.springframework.web.socket.CloseStatus) */ @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { String userId = this.getUserId(session); if(StringUtils.isNoneBlank(userId)){ userMap.remove(userId); System.err.println("This" + userId +"User has been successfully closed"); }else{ System.err.println("When closed, get the user id is empty"); } } /** * This method is called when establishing a websocket connection* @see org.springframework.web.socket.WebSocketHandler#afterConnectionEstablished(org.springframework.web.socket.WebSocketSession) */ @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { String userId = this.getUserId(session); if(StringUtils.isNoneBlank(userId)){ userMap.put(userId, session); session.sendMessage(new TextMessage("WebSocket connection was established successfully!")); } } /** * When the client calls websocket.send, this method will be called for data communication* @see org.springframework.web.socket.WebSocketHandler#handleMessage(org.springframework.web.socket.WebSocketSession, org.springframework.web.socket.WebSocketMessage) */ @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { String msg = message.toString(); String userId = this.getUserId(session); System.err.println("The"+userId+" message sent by the user is: "+msg); message = new TextMessage("The server has received the message, msg="+msg); session.sendMessage(message); } /** * When an exception occurs in the transmission process, call this method* @see org.springframework.web.socket.WebSocketHandler#handleTransportError(org.springframework.web.socket.WebSocketSession, java.lang.Throwable) */ @Override public void handleTransportError(WebSocketSession session, Throwable e) throws Exception { WebSocketMessage<String> message = new TextMessage("Exception message:"+e.getMessage()); session.sendMessage(message); } /** * * @see org.springframework.web.socket.WebSocketHandler#supportsPartialMessages() */ @Override public boolean supportsPartialMessages() { return false; } /** * sendMessageToUser: Send to the specified user* @author zhaoshouyun * @param userId * @param contents * @since JDK 1.7 */ public void sendMessageToUser(String userId,String contents) { WebSocketSession session = userMap.get(userId); if(session !=null && session.isOpen()) { try { TextMessage message = new TextMessage(contents); session.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } } /** * sendMessageToAllUsers: Send to all users* @author zhaoshouyun * @param contents * @since JDK 1.7 */ public void sendMessageToAllUsers(String contents) { Set<String> userIds = userMap.keySet(); for(String userId: userIds) { this.sendMessageToUser(userId, contents); } } /** * getUserId: Get user id * @author zhaoshouyun * @param session * @return * @since JDK 1.7 */ private String getUserId(WebSocketSession session){ try { String userId = (String)session.getAttributes().get(USER_KEY); return userId; } catch (Exception e) { e.printStackTrace(); } return null; } }Step 3: Write websocket-related configuration, of course, you can configure it in xml; I am not using xml configuration now, and I use code configuration, and I need to add a scan package in xml <context:component-scan base-package="com.zsy.websocket" />
/** * Project Name:springRabbitMQ * File Name:WebSocketConfig.java * Package Name:com.zsy.websocket * Date: 1:10:33 pm on January 31, 2018 * Copyright (c) 2018, zhaoshouyun All Rights Reserved. * */ /** * Project Name:springRabbitMQ * File Name:WebSocketConfig.java * Package Name:com.zsy.websocket * Date: 1:10:33 pm on January 31, 2018 * Copyright (c) 2018, zhaoshouyun All Rights Reserved. * */ package com.zsy.websocket; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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; /** * ClassName: WebSocketConfig * Function: TODO ADD FUNCTION. * date: January 31, 2018 at 1:10:33 pm * @author zhaoshouyun * @version * @since JDK 1.7 */ @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { /** * Register handle * @see org.springframework.web.socket.config.annotation.WebSocketConfigurer#registerWebSocketHandlers(org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry) */ @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "/testHandler").addInterceptors(new WebSocketInterceptor()); registry.addHandler(myHandler(), "/socketJs/testHandler").addInterceptors(new WebSocketInterceptor()).withSockJS(); } @Bean public WebSocketHandler myHandler(){ return new MyMessageHandler(); } } Step 4: Write a websocket adapter
package com.zsy.websocket; import java.util.Map; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; /** * ClassName: WebSocketInterceptor * Function: TODO ADD FUNCTION. * date: January 31, 2018 at 11:42:34 am * @author zhaoshouyun * @version * @since JDK 1.7 */ public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor { /** * TODO briefly describes the implementation function of this method (optional). * @see org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor#beforeHandshake(org.springframework.http.server.ServerHttpRequest, org.springframework.http.server.ServerHttpResponse, org.springframework.web.socket.WebSocketHandler, java.util.Map) */ @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { if(request instanceof ServletServerHttpRequest){ ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest)request; //Get parameter String userId = serverHttpRequest .getServletRequest().getParameter("userId"); attributes.put(MyMessageHandler.USER_KEY, userId); } return true; } } The corresponding js in step 5:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <script type="text/javascript"> var websocket; // First determine whether WebSocket is supported if('WebSocket' in window) { websocket = new WebSocket("ws://localhost:8085/springTest/testHandler?userId=zhaoshouyun"); } else if('MozWebSocket' in window) { websocket = new MozWebSocket("ws://localhost:8085/springTest/testHandler?userId=zhaoshouyun"); } else { websocket = new SockJS("http://localhost:8085/springTest/socketJs/testHandler?userId=zhaoshouyun"); } // When opening the connection, websocket.onopen = function(evnt) { console.log(" websocket.onopen "); }; // When receiving the message, websocket.onmessage = function(evnt) { alert(evnt.data); }; websocket.onerror = function(evnt) { console.log(" websocket.onerror "); }; websocket.onclose = function(evnt) { console.log(" websocket.onclose "); }; function says(){ //The client actively sends a message websocket.send(document.getElementById('msg').value); } </script> </head> <body> <input type="text" value="" id="msg"><button onclick="say()"></button> </body> </html> Step 6 Test:
package com.zsy.test.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.zsy.websocket.MyMessageHandler; /** * ClassName: TestController * Function: TODO ADD FUNCTION. * date: December 14, 2017 at 11:11:23 am * @author zhaoshouyun * @version * @since JDK 1.7 */ @Controller public class TestController { @Autowired MyMessageHandler handler; @RequestMapping("/get") public String get(){ return "index"; } @ResponseBody @RequestMapping("/get1") public String send(String name){ handler.sendMessageToUser("zhaoshouyun", "Content sent by the server:"+name); return "success"; } }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.