Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The detailed flow of how SpringBoot WebSocket monitors exceptions in real time.

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "the detailed flow of how to monitor exceptions in real time by SpringBoot WebSocket". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "SpringBoot WebSocket how to monitor the detailed flow of exceptions in real time"!

Catalogue

Write at the front

Achieve:

Front end:

Backend:

test

Write at the front

This exception is not another exception, and the exception mentioned in the title is a business exception.

Recently made a demand, fire equipment inspection, if the inspection found abnormal, submitted through the mobile phone, the background real-time monitoring page to get the equipment information and location in real time, and then arrange for the staff to deal with it.

Because the server is required to actively send messages to the client, it is easy to think of using WebSocket to achieve this function.

WebSocket will not make introductions.

The front end is slightly complex, which requires mouse tracing to locate each device on a location distribution map and rendering according to different screen sizes. This article does not introduce it, but simply uses the page style to render the effect.

Green for normal, red for abnormal

Expected effect: before receiving the request, an exception with-> id of 3 was submitted, and Wang Wu with an id of 3 turned red

Implementation: front end:

Paste the code directly

Real-time monitoring .item {display: flex; border-bottom: 1px solid # 000000; justify-content: space-between; width: 30%; line-height: 50px; height: 50px;} .item span:nth-child (2) {margin-right: 10px; margin-top: 15px Width: 20px; height: 20px; border-radius: 50%; background: # 55ff00;} .nowI {background: # ff0000! important } {{item.id}}. {{item.name}} var vm = new Vue ({el: "# app", data: {list: [{id: 1 Name: 'Zhang San', state: 1}, {id: 2, name:'Li Si', state: 1} {id: 3, name: 'Wang Wu', state: 1}, {id: 4, name: 'Han Meimei' State: 1}, {id: 5, name:'Li Lei', state: 1},]}) var webSocket = null If ('WebSocket' in window) {/ / create WebSocket object webSocket = new WebSocket ("ws://localhost:18801/webSocket/" + getUUID ()); / / connected successfully webSocket.onopen = function () {console.log ("connected") WebSocket.send ("messaging Test")} / / received the message webSocket.onmessage = function (msg) {/ / processing the message var serverMsg = msg.data Var t_id = parseInt (serverMsg) / / message sent from the server, ID,string needs to be converted to int type to compare for (var I = 0; I)

< vm.list.length; i++) { var item = vm.list[i]; if(item.id == t_id){ item.state = -1; vm.list.splice(i,1,item) break; } } }; //关闭事件 webSocket.onclose = function() { console.log("websocket已关闭"); }; //发生了错误事件 webSocket.onerror = function() { console.log("websocket发生了错误"); } } else { alert("很遗憾,您的浏览器不支持WebSocket!") } function getUUID() { //获取唯一的UUID return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } 后端: 项目结构是这样子的,后面的代码关键注释都有,就不重复描述了

1. Create a new SpringBoot project and select web and WebSocket dependency.

2. Configure application.yml

# Port server: port: 1880 password. Because the API does not require permission, a password is added to verify mySocket: myPwd: jae_123

3. WebSocketConfig configuration class

@ Configurationpublic class WebSocketConfig {/ * injects a ServerEndpointExporter that automatically registers websocket endpoint * / @ Bean public ServerEndpointExporter serverEndpointExporter () {return new ServerEndpointExporter ();} declared with the @ ServerEndpoint annotation.

4. WebSocketServer class, which is used for the interaction between server and client.

/ * * @ author jae * @ ServerEndpoint ("/ webSocket/ {uid}") the front end establishes a link with the backend through this URI * / @ ServerEndpoint ("/ webSocket/ {uid}") @ Componentpublic class WebSocketServer {private static Logger log = LoggerFactory.getLogger (WebSocketServer.class); / / static variable, which is used to record the current number of online connections. It should be designed to be thread safe. Private static final AtomicInteger onlineNum = new AtomicInteger (0); / / Thread-safe Set of the concurrent package, which is used to hold the corresponding WebSocketServer object for each client. Private static CopyOnWriteArraySet sessionPools = new CopyOnWriteArraySet (); / * client connection succeeded * / @ OnOpen public void onOpen (Session session, @ PathParam (value = "uid") String uid) {sessionPools.add (session); onlineNum.incrementAndGet (); log.info (uid + "join webSocket! The current number is "+ onlineNum);} / * * the method called by connection closure * / @ OnClose public void onClose (Session session) {sessionPools.remove (session); int cnt = onlineNum.decrementAndGet (); log.info (" connection closed, the current number of connections is: {} ", cnt) } / * send message * / public void sendMessage (Session session, String message) throws IOException {if (session! = null) {synchronized (session) {session.getBasicRemote () .sendText (message) } / * Mass messaging * / public void broadCastInfo (String message) throws IOException {for (Session session: sessionPools) {if (session.isOpen ()) {sendMessage (session, message) Error * / @ OnError public void onError (Session session, Throwable throwable) {log.error ("error occurs"); throwable.printStackTrace ();}}

5. WebSocketController class, which is used for interface testing

@ RestController@RequestMapping ("/ open/socket") public class WebSocketController {@ Value ("${mySocket.myPwd}") public String myPwd; @ Autowired private WebSocketServer webSocketServer / * Mobile client request interface * @ param id the ID * @ param pwd password of the device where an exception occurs (remember to encrypt it in actual development) * @ throws IOException * / @ PostMapping (value = "/ onReceive") public void onReceive (String id,String pwd) throws IOException {if (pwd.equals (myPwd)) {/ / password verification is consistent (here is an example The actual development also needs to have a password encrypted check), then send webSocketServer.broadCastInfo (id) in groups. }} Test

1. Open the front-end page and connect with WebSocket

Console output, connected successfully

2. Because it is simulated data, all the display is normal, and there is no exception when the page is submitted.

3. Next, we use the interface test tool Postman to submit an exception

Notice the state change of this data with an id of 3

We can see that the status of Wang Wu with an id of 3 has become abnormal, and the real-time communication has been successful.

At this point, I believe you have a deeper understanding of "SpringBoot WebSocket how to monitor the detailed flow of exceptions in real time". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report