1. The practical effect
2. Add a WebSocketConfig
Package com.llltony.springboot.config; Import org.springframework.context.annotation.Bean; Import org.springframework.stereotype.Component; Import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Component public class WebSocketConfig { / ** * serverEndpointExporter action * * the Bean will be automatically registered for use @ServerEndpoint comment Endpoint declared the WebSocket * * @return * / @Bean public serverEndpointExporter serverEndpointExporter () { return new new serverEndpointExporter (); } }
3. Add WebSocket class
Package com.llltony.springboot.socket; Import com.alibaba.fastjson.JSONObject; Import lombok.extern.slf4j.Slf4j; Import org.springframework.stereotype.Component; Import javax.websocket.OnClose; Import javax.websocket.OnMessage; Import javax.websocket.OnOpen; Import javax.websocket.Session; Import javax.websocket.server.PathParam; Import javax.websocket.server.ServerEndpoint; Import java.util.concurrent.ConcurrentHashMap; / ** * this comment has @ServerEndpoint What is the role? * <P> * this annotation is used to identify the class acting, its main function is identified as the current class of service end a WebSocket * The value of the client user annotation connection to access the URL address * / @ SLF4J @Component @ServerEndpoint ( "/ the WebSocket / {name}" ) public class the WebSocket { / ** * connection conversation with a client, you need to pass it to send a message to the client * / Private the Session the session; / ** * identifies the currently connected client user name * / Private String name; / ** * for storing all connection services client, this object store is safe * / Private static of ConcurrentHashMap <String, a WebSocket> = webSocketSet new new of ConcurrentHashMap <> (); @OnOpen public void the OnOpen (the session the Session, @PathParam (value = "name") {String name) the this the .session = the session; the this .name = name; // name is used to represent the only client, if you need to specify the transmission, transmission needs to be distinguished by the specified name webSocketSet.put (name, the this ); log .info (name + "[a WebSocket] successful connection, the current connection number: = {}" , webSocketSet.size ()); } @OnClose public void the OnClose () { webSocketSet.remove ( the this .name); log.info (name + "[a WebSocket] exit successful, the current number of connection: = {}" , webSocketSet.size ()); } @OnMessage public void the OnMessage (String Message) { log.info ( "[a WebSocket] receive the message: {}" , Message); // The transmission user name is determined to know the JSONObject JSON = JSONObject.parseObject (Message); String name = json.get ( "username" ) .toString (); String Content = json.get ( "Content" ) .toString (); IF (!! name.equals ( "") && name = null ) { AppointSending (name, Content); } the else { GroupSending (Message) ; } } / ** * mass * * @param Message * / public void GroupSending(String message) { for (String name : webSocketSet.keySet()) { try { webSocketSet.get(name).session.getBasicRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } } /** * 指定发送 * * @param name * @param message */ public void AppointSending(String name, String message) { try { webSocketSet.get(name).session.getBasicRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } }
4. Add dependent pom
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!-- fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
5. Add html page test call
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>websocket_Test</title> <script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script> <meta content="no-cache" http-equiv="pragma"> <meta content="no-cache" http-equiv="cache-control"> <meta content="0" http-equiv="expires"> <meta content="keyword1,keyword2,keyword3" http-equiv="keywords"> <meta content="This is my page" http-equiv="description"> </head> <body> <div> <h3>testing...</h3> <div id="msgtext"> </div> <div> <INPUT ID = "username" name = "username" type = "text" placeholder = "Please enter a user name" /> < Button the onclick = "connectWebSocket ();" > connected to a WebSocket </ Button > < br > < INPUT ID = "MSG" name = "MSG" type = "text" placeholder = "Please enter information occurs" /> < Button the onclick = "the sendmsg ();" > transmission </button> </div> </div> </body> <script type="text/javascript"> var ws; function connectWebSocket(){ if('WebSocket' in window){ var url="ws://localhost:8080/websocket/"; var username=$('#username').val(); if(username=="" || username==null){ Alert ( " Please enter the user name " ); return ; } the else { URL = URL + username; } WS = new new a WebSocket (URL); } the else { Alert ( " not supported WebSocket " ); } ws.onopen = function (EVT ) { // Alert ( "OP"); } ws.onclose = function(evt){ alert("close"); } ws.onmessage = function(evt){ var msg = evt.data; if("[object Blob]" != msg){ var msgdiv = document.getElementById("msgtext"); var span = document.createElement("span"); span.innerHTML = msg+"<br />"; msgdiv.appendChild(span); }else{ var msgdiv = document.getElementById("msgtext"); var span = document.createElement("span"); var br = document.createElement("br"); var can = document.createElement("canvas"); var context = can.getContext("2d"); var image = new Image(); image.onload = function () { //image.height context.clearRect(0, 0, can.width, can.height); context.drawImage(image, 0, 0, can.width, can.height); } image.src = URL.createObjectURL(msg); span.appendChild(can); span.appendChild(br); msgdiv.appendChild(span); } } ws.onerror = function(evt){ alert("error"); } } function sendmsg(){ var message={}; message.content="("+new Date().toLocaleTimeString()+")<br />"+document.getElementById("msg").value; message.username=$('#username').val(); ws.send(JSON.stringify(message)); } </script> </html>
6. The back-end code in the call to send a message websocket
7. Source: https://github.com/CodingPandaLLL/tsl.git (dev_webSocket branch in)