Real-Time Monitoring System Using WebSocket with Vue Frontend and SpringBoot Backend

This article demonstrates how to build a real‑time equipment monitoring application by using WebSocket for server‑client communication, a Vue.js front‑end to display device status, and a SpringBoot back‑end that broadcasts alerts when abnormal devices are reported.

Architect's Guide
Architect's Guide
Architect's Guide
Real-Time Monitoring System Using WebSocket with Vue Frontend and SpringBoot Backend

This guide describes the development of a real‑time monitoring system for fire‑equipment inspections, where abnormal device reports submitted from a mobile client are pushed instantly to a web dashboard using WebSocket.

Implementation

Front‑end

The front‑end is a simple Vue.js page that lists devices and changes the background color of a device to red when its state becomes abnormal.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>实时监控</title>
    </head>
    <style>
        .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;
        }
    </style>
    <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>
    </body>
    <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(){    //获取唯一的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);
            });
        }
    </script>
</html>

Back‑end

The back‑end is a SpringBoot application with WebSocket support.

1. Create a SpringBoot project with web and WebSocket dependencies.

2. Configure application.yml:

#端口
server:
  port: 18801

#密码,因为接口不需要权限,所以加了个密码做校验
mySocket:
  myPwd: jae_123

3. Add a WebSocketConfig class to register the endpoint:

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

4. Implement WebSocketServer to manage connections and broadcast messages:

@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 CopyOnWriteArraySet<Session> sessionPools = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "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();
    }
}

5. Provide a WebSocketController for the mobile client to report abnormal devices:

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

    @Autowired
    private WebSocketServer webSocketServer;

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

Testing

1. Open the front‑end page; the console shows a successful WebSocket connection.

2. Initially all devices appear normal (green).

3. Use Postman to POST an abnormal device ID (e.g., id=3) to /open/socket/onReceive with the correct password.

4. The device with ID 3 changes its background to red, confirming real‑time push works.

Reference: MDN WebSocket Documentation
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.

BackendjavaVuereal-time monitoringWebSocketSpringBoot
Architect's Guide
Written by

Architect's Guide

Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.

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.