1, What is WebSocket
WebSocket: communication between client and server
WebSocket makes the data exchange between the client and the server easier, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete one handshake, and they can directly create a persistent connection and carry out two-way data transmission.
Now, in order to implement push technology, many websites use Ajax polling technology. Polling is a specific time interval (such as every 1 second), the browser sends HTTP request to the server, and then the server returns the latest data to the browser of the client. This traditional mode brings obvious disadvantages, that is, the browser needs to send requests to the server constantly, but HTTP requests may contain a long header, in which the real effective data may only be a small part, obviously this will waste a lot of bandwidth and other resources.
The WebSocket protocol defined by HTML5 can save server resources and bandwidth, and can communicate in real time.
2, WebSocket implementation
Front end code
stay list.ftl Join in
<script> var websocket = null; //Determine whether the browser supports if('WebSocket' in window) { websocket = new WebSocket('ws://localhost:8080/sell/webSocket'); }else { alert('This browser does not support websocket!'); } //WebSocket event websocket.onopen = function (event) { console.log('Establish a connection'); } websocket.onclose = function (event) { console.log('Connection closed'); } websocket.onmessage = function (event) { console.log('Message received:' + event.data) //Pop up reminder (find the front-end code in ibootstrap and copy it to list.ftl Medium) $('#myModal').modal('show'); // Play music document.getElementById('notice').play(); } websocket.onerror = function () { alert('websocket Communication error!');//Popup } window.onbeforeunload = function () { websocket.close();//close } </script>
Back end code
1. Import dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2. Inject serverendpoint exporter (injection environment)
@Component public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
3. Write WebSocket class (under service package, but not service)
@Component @ServerEndpoint("/webSocket") @Slf4j public class WebSocket { //WebSocket container private Session session; //The thread safe Set of the concurrent package is used to store the MyWebSocket object corresponding to each client. To realize the communication between the server and the single client, Map can be used for storage, where Key can be the user ID private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>(); /** * Connection established successfully * session To connect to a client, you need to send data to the client through it */ @OnOpen public void onOpen(Session session) { this.session = session; webSocketSet.add(this); log.info("[websocket Message] has a new connection, total:{}", webSocketSet.size()); } /** * Close connection */ @OnClose public void onClose() { webSocketSet.remove(this); log.info("[websocket Message] disconnected, total:{}", webSocketSet.size()); } /** * Client message received * message Messages sent by clients */ @OnMessage public void onMessage(String message) { log.info("[websocket Message] received the message from the client:{}", message); } /** * send message */ public void sendMessage(String message) { for (WebSocket webSocket: webSocketSet) { log.info("[websocket Message] broadcast message, message={}", message); try { webSocket.session.getBasicRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } } }
4. Send a message when creating an order
Test: create an order
Front end display:
Popup
Console output: