How to Build Real‑Time Device Monitoring with WebSocket and Spring Boot

This article demonstrates how to implement a real‑time device‑monitoring system using WebSocket, covering the problem scenario, front‑end Vue.js visualization, Spring Boot back‑end configuration, WebSocket server setup, and step‑by‑step testing to achieve instant status updates.

Architect
Architect
Architect
How to Build Real‑Time Device Monitoring with WebSocket and Spring Boot

Background

Need real‑time push for fire‑equipment inspection: when a mobile client submits an abnormal status, the back‑office page must update instantly. WebSocket is chosen over HTTP polling.

Front‑end implementation (Vue.js)

The device list is rendered with a colored indicator (green for normal, red for abnormal). A WebSocket connection is opened on page load, receives a device ID, and updates the corresponding item state to -1 (red).

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8"/>
  <title>实时监控</title>
  <style>
    .item { display:flex; border-bottom:1px solid #000; justify-content:space-between; width:30%; line-height:50px; height:50px; }
    .itemspan:nth-child(2) { margin-right:10px; margin-top:15px; width:20px; height:20px; border-radius:50%; background:#55ff00; }
    .nowI { background:#ff0000 !important; }
  </style>
</head>
<body>
  <div id="app">
    <div v-for="item in list" class="item">
      <span>{{item.id}}.{{item.name}}</span>
      <span :class='item.state==-1?"nowI":""'></span>
    </div>
  </div>
  <script src="./js/vue.min.js"></script>
  <script type="text/javascript">
    var vm = new Vue({
      el: "#app",
      data: { list: [
        {id:1, name:'张三', state:1},
        {id:2, name:'李四', state:1},
        {id:3, name:'王五', state:1},
        {id:4, name:'韩梅梅', state:1},
        {id:5, name:'李磊', state:1}
      ]}
    });
    var webSocket = null;
    if ('WebSocket' in window) {
      webSocket = new WebSocket("ws://localhost:18801/webSocket/" + getUUID());
      webSocket.onopen = function(){ console.log("已连接"); webSocket.send("消息发送测试"); };
      webSocket.onmessage = function(msg){
        var serverMsg = msg.data;
        var t_id = parseInt(serverMsg);
        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(){
      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);
      });
    }
  </script>
</body>
</html>

Back‑end setup (Spring Boot)

Dependencies: spring-boot-starter-web and spring-boot-starter-websocket. Core files:

application.yml

server:
  port: 18801

mySocket:
  myPwd: jae_123

WebSocketConfig.java

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

WebSocketServer.java

@ServerEndpoint("/webSocket/{uid}")
@Component
public class WebSocketServer {
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    private static final AtomicInteger onlineNum = new AtomicInteger(0);
    private static final CopyOnWriteArraySet<Session> sessionPools = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("uid") String uid) {
        sessionPools.add(session);
        onlineNum.incrementAndGet();
        log.info(uid + " 加入了 WebSocket,当前在线人数为 " + onlineNum);
    }

    @OnClose
    public void onClose(Session session) {
        sessionPools.remove(session);
        int cnt = onlineNum.decrementAndGet();
        log.info("有连接关闭,当前连接数为:" + cnt);
    }

    public void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    public void broadCastInfo(String message) throws IOException {
        for (Session session : sessionPools) {
            if (session.isOpen()) {
                sendMessage(session, message);
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("发生了错误");
        throwable.printStackTrace();
    }
}

WebSocketController.java

@RestController
@RequestMapping("/open/socket")
public class WebSocketController {
    @Value("${mySocket.myPwd}")
    private String myPwd;

    @Autowired
    private WebSocketServer webSocketServer;

    @PostMapping("/onReceive")
    public void onReceive(String id, String pwd) throws IOException {
        if (pwd.equals(myPwd)) {
            webSocketServer.broadCastInfo(id);
        }
    }
}

Testing the flow

Open the front‑end page; the browser creates a WebSocket connection and logs “已连接”.

All devices show the green indicator.

Send a POST request to /open/socket/onReceive (e.g., via Postman) with id=3 and the configured password.

The server broadcasts the ID, the front‑end receives it, updates device 3’s state to -1, and the indicator turns red.

Conclusion

WebSocket provides a lightweight, low‑latency mechanism for pushing real‑time status updates from back‑end to front‑end, eliminating the need for frequent HTTP polling. The implementation uses standard Spring Boot and Vue.js components and can be adapted to other monitoring scenarios.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javafrontend developmentBackend DevelopmentSpring Bootreal-time monitoringWebSocketVue.js
Architect
Written by

Architect

Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.