WebSocket realizes front and rear communication

Posted by toledojimenez on Thu, 20 Jan 2022 12:06:29 +0100

Introduction: we launched a mall project. After it was handed over to the operation team, they asked the mall to add a voice prompt when new orders came, so that they can know in time vb.net tutorial Here comes the order. I think about whether this requirement is completed at the back end or at the front end, but when I think about it carefully, whether it is completed at the front end or at the back end, the demand is doomed to be thrown out, because there is no front-end Engineer in the back-end management of the mall, and the front-end and back-end work is completed by a back-end engineer. This also makes the front-end interface ugly, including the front-end code style ~ because this c# tutorial This is the first time I have written so many front-end code projects ~ ha ha ~ dare me to write ~ I dare to write.

1, Idea:

1. The platform realizes push, which is the top project python basic tutorial Ajax polling technology has been used. In this way, the browser needs to constantly send requests to the server, which will waste a lot of bandwidth and other resources. The technology is feasible but not very good.

2. This requirement is completely realized in the front end. The front end monitors the changes of elements in the order list, circularly traverses the order list or uses Vue's Watch to monitor. When there are new elements in the order list, you can call the play sound API. It doesn't feel very reliable. I haven't tried.

3. WebSocket is a protocol for full duplex communication on a single TCP connection provided by HTML5, which can better save server resources and bandwidth, and communicate in real time. WebSocket makes data exchange between client and server easier java basic course More simply, it allows the server to actively push data to the client. In the WebSocket API, the browser and the server only need to complete a handshake, and they can directly create a persistent connection - long connection and conduct two-way data transmission. I guess the most important reason for using this scheme is that back-end development is my better field.

2, SpringBoot/SpringCloud integration WebSocket

1. Introducing WebSocket Jar package

In the POM of the SpringBoot project that requires WebSocket communication The WebSocket Jar package is introduced into the XML file.

1       <!-- test websocket -->
2         <dependency>
3             <groupId>org.springframework.boot</groupId>
4             <artifactId>spring-boot-starter-websocket</artifactId>
5         </dependency>    

2. Create WebSocket configuration class

This configuration class is used to detect annotated @ ServerEndpoint bean s and register them in the container.

 1 package com.tjt.mall.config;
 2 
 3 import lombok.extern.slf4j.Slf4j;
 4 import org.springframework.context.annotation.Bean;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.web.socket.server.standard.ServerEndpointExporter;
 7 
 8 
 9 @Configuration
10 @Slf4j
11 public class WebSocketConfig {
12     /**
13      * Inject the ServerEndpointExporter object into the spring container
14      * Equivalent to xml:
15      * <beans>
16      * <bean id="serverEndpointExporter" class="org.springframework.web.socket.server.standard.ServerEndpointExporter"/>
17      * </beans>
18      * <p>
19      * Detect all bean s annotated with @ serverEndpoint and register them.
20      *
21      * @return
22      */
23     @Bean
24     public ServerEndpointExporter serverEndpointExporter() {
25         log.info("serverEndpointExporter Injected");
26         return new ServerEndpointExporter();
27     }
28 }

3. Create WebSocket processing class

The WebSocket processing class needs to use @ ServerEndpoint annotation to listen for connection establishment, closing and message reception in this class.

  1 package com..mall.config;
  2 
  3 import org.slf4j.Logger;
  4 import org.slf4j.LoggerFactory;
  5 import org.springframework.stereotype.Component;
  6 
  7 import javax.annotation.PostConstruct;
  8 import javax.websocket.*;
  9 import javax.websocket.server.ServerEndpoint;
 10 import java.io.IOException;
 11 import java.util.concurrent.CopyOnWriteArraySet;
 12 import java.util.concurrent.atomic.AtomicInteger;
 13 
 14 @ServerEndpoint(value = "/ws/path/asset")    // WebSocket path
 15 @Component
 16 public class WebSocketServer {
 17 
 18     private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
 19     private static final AtomicInteger OnlineCount = new AtomicInteger(0);
 20     // The thread safe Set of concurrent package is used to store the Session object corresponding to each client.
 21     private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();
 22 
 23     @PostConstruct
 24     public void init() {
 25         log.info("websocket load");
 26     }
 27 
 28 
 29     /**
 30      * Method successfully called for connection establishment
 31      */
 32     @OnOpen
 33     public void onOpen(Session session) throws IOException{
 34         SessionSet.add(session);
 35         int cnt = OnlineCount.incrementAndGet(); // Online number plus 1
 36         log.info("There are connections joined. The current number of connections is:{}", cnt);
 37        // SendMessage(session, "connection succeeded");
 38     }
 39 
 40     /**
 41      * Method called for connection closure
 42      */
 43     @OnClose
 44     public void onClose(Session session) {
 45         SessionSet.remove(session);
 46         int cnt = OnlineCount.decrementAndGet();
 47         log.info("There are connections closed. The current number of connections is:{}", cnt);
 48     }
 49 
 50     /**
 51      * Method of calling after receiving client message
 52      *
 53      * @param message
 54      *            Messages sent by the client
 55      */
 56     @OnMessage
 57     public void onMessage(String message, Session session) throws IOException {
 58         log.info("Message from client:{}",message);
 59         SendMessage(session, "Received message, message content:"+message);
 60 
 61     }
 62 
 63     /**
 64      * An error occurred
 65      * @param session
 66      * @param error
 67      */
 68     @OnError
 69     public void onError(Session session, Throwable error) {
 70         log.error("An error occurred:{},Session ID:  {}",error.getMessage(),session.getId());
 71         error.printStackTrace();
 72     }
 73 
 74     /**
 75      * Send a message. Practice shows that the session will change every time the browser refreshes.
 76      * @param session
 77      * @param message
 78      */
 79     public static void SendMessage(Session session, String message) throws IOException {
 80         try {
 81 //          session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)",message,session.getId()));
 82             session.getBasicRemote().sendText(message);
 83         } catch (IOException e) {
 84             log.error("Error sending message:{}", e.getMessage());
 85             e.printStackTrace();
 86         }
 87     }
 88 
 89     /**
 90      * Mass messaging
 91      * @param message
 92      * @throws IOException
 93      */
 94     public static void BroadCastInfo(String message) throws IOException {
 95         for (Session session : SessionSet) {
 96             if(session.isOpen()){
 97                 SendMessage(session, message);
 98             }
 99         }
100     }
101 
102     /**
103      * Specify the Session to send the message
104      * @param sessionId
105      * @param message
106      * @throws IOException
107      */
108     public static void SendMessage(String message,String sessionId) throws IOException {
109         Session session = null;
110         for (Session s : SessionSet) {
111             if(s.getId().equals(sessionId)){
112                 session = s;
113                 break;
114             }
115         }
116         if(session!=null){
117             SendMessage(session, message);
118         }
119         else{
120             log.warn("The name you specified was not found ID Session:{}",sessionId);
121         }
122     }
123 }

4. Call WebSocket to send message

After the code generated by the order, call the method of mass sending or separate sending messages in the WebSocket processing class according to the demand.

1         log.info("shopping cart generates order OK: {}", result);
2         // send webSocket message
3         WebSocketServer.BroadCastInfo("after service order");        

3, VUE integrates WebSocket s

When using WebSocket at the front end, you still need to judge, because although most browsers support WebSocket, such as Chrome, Mozilla, Opera and Safari, a few do not support it.

1. Operating WebSocket in HTML

Establish a WebSocket connection in the HTML page. As for when to connect to WebSocket, it depends on your personal needs. After I log in successfully, that is, I connect to WebSocket in HTML on the login page and listen for messages.

I deleted some codes in the login HTML page, leaving only the codes related to WebSocket operations and playing sound effects.

 1 <template>
 2   <div class="dashboard-container">
 3   <!--    stay div Introducing audio resources into-->
 4     <audio ref="audio" src="@/assets/voice/tjtVoice.mp3"></audio>
 5   </div>
 6 </template>
 7 
 8 <script>
 9 
10 export default {
11 
12 created() {
13     this.playVoice()
14   },
15 
16   methods: {
17     playVoice() {
18       var socket;
19       // Use that when the handle object, that is, the audio resource, cannot be found
20       let that = this
21       if (typeof (WebSocket) == "undefined") {
22         console.log("Sorry: your browser does not support WebSocket");
23       } else {
24         console.log("Congratulations: your browser supports WebSocket");
25         //Implementing WebSocket objects
26         //Specify the server address to connect and establish a connection with the port
27         //Note that ws and wss use different ports. I test with a self signed certificate,
28         //Unable to use wss. An error occurs when the browser opens WebSocket
29         //ws corresponds to http and wss corresponds to https.
30           socket = new WebSocket("ws://localhost:11200/ws/path/asset");
31         //Connection open event
32         socket.onopen = function() {
33           console.log("Socket Opened");
34           // socket.send("message sending test (From Client)");
35 
36         };
37         //Message received event
38         socket.onmessage = msg => {
39           // When a message is received, call the play audio resource API
40            console.log(msg.data);
41            this.$refs.audio.play()
42         };
43         //Connection close event
44         socket.onclose = function() {
45           console.log("Socket Closed");
46         };
47         //An error event occurred
48         socket.onerror = function() {
49           alert("Socket An error has occurred");
50         }
51         //Close the connection when the window closes
52         window.unload=function() {
53          // socket.close();
54         };
55       }
56     }
57   }
58 
59 }
60 </script>

4, Test effect

1. Start the SpringBoot project equipped with WebSocket.

2. Start the VUE project, click login and connect to WebSocket.

Backend engineering console printing

[2021-07-07 08:45:47] [INFO] - there are connections. The current number of connections is: 1

Front end browsing sql tutorial The WebSocket connection status is displayed under the WS of the browser:

3. Simulate order generation and call the order generation interface API in the background.

The front-end browser Console prints, successfully listens to the section and receives the WebSocket message sent by the back-end.

4. Audio audition

After receiving the WebSocket message sent by the back end, play the sound effect immediately.

IV. audio resources

Download link: https://pan.baidu.com/s/1rqa6Uift3RpWShPytgBLgQ 

Password: 8arh