1, the introduction of dependency:
<!-- webSocket --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <!-- thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2, thymeleaf configuration:
Thymeleaf:
encoding: UTF-8
# default path
prefix: the CLASSPATH: / Templates /
# suffix
suffix: .html
# template mode, support for HTML, XML TEXT JAVASCRIPT
the MODE: HTML5
# development configuration is false, but also to avoid modify the template to restart the server
cache: false
3, configuration class:
/** * 开启 webSocket 支持 */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter () { return new ServerEndpointExporter(); } }
@ServerEndpoint (value = "/ WS / Asset" ) @Component public class WebSocketServer { @PostConstruct public void the init () { System.out.println ( "a WebSocket loading" ); } Private static Logger LoggerFactory.getLogger = log (WebSocketServer. class ); Private static Final of AtomicInteger OnlineCount = new new of AtomicInteger (0 ); // Concurrent security thread package Set, each used to store the Session object corresponding to the client. Private static CopyOnWriteArraySet <the Session> = SessionSet new newCopyOnWriteArraySet <the Session> ; () / ** Method * client connection is established is called * @param the session * / @OnOpen public void the onOpen (the Session the session) { SessionSet.add (the session); int CNT = OnlineCount.incrementAndGet () ; // online plus. 1 log.info ( "join connection, the current connection number: {}" , CNT); the sendMessage (the session, "connection successful" ); } / * Close method called client connections * * @param the session * / @OnClose public void int the onClose (the Session the session) { SessionSet.remove (the session); CNT = OnlineCount.decrementAndGet (); log.info ( "close connection, the current connection number: {}" , CNT); } / ** * method call after receiving the client message * @param message sent by the client's message * @param the session * / @OnMessage public void the onMessage (String message, the Session the session) { log.info ( "message from the client: {}" , message); the sendMessage (the session, "message is received, the message content:" + message); } / ** * error * @param the session *@param error * / @OnError public void the onError (the Session the session, the Throwable error) { log.error ( "Error: {}, the Session ID: {}" , error.getMessage (), session.getId ()); error .printStackTrace (); } / ** * push message server (refreshed every browser, session vary) * @param the session * @param message * / public static void the sendMessage (the session the Session, String message) { the try { session.getBasicRemote (). sendText, (String.format ( "% S (the From Server, the Session ID =% S)" , Message, session.getId ())); } The catch (IOException E) { log.error ( "Send Message Error: {}" , e.getMessage ()); e.printStackTrace (); } } / ** * Group messaging server * @param Message * @throws IOException * / public static void broadCastInfo (String Message) throws IOException { for (the session the Session: SessionSet) { IF (session.isOpen ()) { the sendMessage (the session, Message); } } } / ** * 服务端指定 Session 推送消息 * @param sessionId * @param message * @throws IOException */ public static void sendMessage(String message, String sessionId) throws IOException { Session session = null; for (Session s : SessionSet) { if(s.getId().equals(sessionId)){ session = s; break; } } IF (the session =! null) { The sendMessage (the session, Message); } the else { log.warn ( "you did not find the specified session ID: {}" , sessionId); } } }
4, Controller categories:
@Controller @RequestMapping("/template") public class TemplateController { // 跳转到 webSocket 测试页面 @RequestMapping("/webSocket") public String websocket(ModelMap map) { return "websocket/index.html"; } }
@RestController @RequestMapping("/api/ws") public class WebSocketController { /** * 群发消息内容 * @param message * @return */ @RequestMapping(value="/sendAll", method=RequestMethod.GET) public String sendAllMessage(@RequestParam String message){ try { WebSocketServer.broadCastInfo(message); } catch (IOException e) { e.printStackTrace(); } return "OK"; } /** Message specifies the session ID * * @param Message Message Content * @param ID connection session ID * @return * / @RequestMapping (value = "/ sendOne", Method = RequestMethod.GET) public String sendOneMessage (String Message @RequestParam, @ String ID RequestParam) { the try { WebSocketServer.sendMessage (Message, ID); } the catch (IOException E) { e.printStackTrace (); } return "the OK" ; } }
5, the test page:
<! DOCTYPE HTML > < HTML lang = "EN" > < head > < Meta charset = "UTF-. 8" > < title > WebSocket Test </ title > </ head > < body > < H3 > a WebSocket test, the < span style = "Color: Red" > console </ span > to view the test information output! </ H3 > < IF ( typeof (the WebSocket) == " undefined " ) { console.log ( " sorry: your browser does not support the WebSocket " ); } the else { console.log ( " Congratulations: Your browser supports the WebSocket " ); / / instantiate an object WebSocket // specify the server address and port to connect to establish a connection // Note ws, wss use a different port. I use a self-signed certificate test, // can not use wss, error when the browser opens the WebSocket // WS correspond http, wss correspond https. Socket = new new a WebSocket ( " WS: // localhost: 8087 / WS / Asset " ); // open connections event socket.onopen = function () { the console.log ( " the Socket open " ); socket.send ( " message sending test (the From Client) " ); }; // received event message socket.onmessage = function (MSG) { the console.log (msg.data); }; // connector off event socket.onclose = function () { the console.log ( " the Socket closed " ); }; // an error occurred event socket.onerror = function () { Alert ( " the Socket error has occurred " ); } // window is closed, closes the connection window.unload = function () { the Socket.close (); }; } </ Script > </ body > </ HTML >
6. Verify that effect: