1. 程式人生 > >WebSocket 實時更新mysql資料到頁面

WebSocket 實時更新mysql資料到頁面

使用websocket的初衷是,要實時更新mysql中的報警資訊到web頁面顯示
沒怎麼碰過web,程式碼寫的是真爛,不過也算是功能實現了,放在這裡也是鞭策自己,web也要多下些功夫

準備

引入依賴

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>
<dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency>

先看看mysql中資料的格式

這裡寫圖片描述

資料封裝

public class AlarmMessage {
    private String fanNo;
    private
String time; private String description; public AlarmMessage(String fanNo, String time, String description) { this.fanNo = fanNo; this.time = time; this.description = description; } public String getFanNo() { return fanNo; } public String getTime
() { return time; } public String getDescription() { return description; } }

jdbc從資料庫中讀取資料

public class DBUtil {

    public List<AlarmMessage> getFromDB() throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        List<AlarmMessage> list=new ArrayList<AlarmMessage>();

        String dirver="com.mysql.jdbc.Driver";
        String user="root";
        String psd="root";
        String database="streamingproblem";
        String tablename="problem";
        String url="jdbc:mysql://172.17.11.120:3306/"+database+"?user="+user+"&password="+psd;
        Class.forName(dirver).newInstance();
        Connection conn= DriverManager.getConnection(url);
        Statement stat=conn.createStatement();
        String sql="select * from "+tablename;
        ResultSet rs=stat.executeQuery(sql);
        while (rs.next()){
            AlarmMessage alarmMessage=new AlarmMessage(rs.getString(2),rs.getString(3),rs.getString(4));
            list.add(alarmMessage);
        }
        rs.close();
        stat.close();
        conn.close();
        return list;
    }

}

開始寫websocket

寫一個執行緒用於傳送新資料到頁面,run中開啟無限迴圈,用一個變數 currentIndex 記錄當前資料量,當有新資料時,傳送新資料

import javax.websocket.Session;

public class OneThread extends Thread {

    private Session session;
    private List<AlarmMessage> currentMessage;
    private DBUtil dbUtil;
    private int currentIndex;

    public OneThread(Session session) {
        this.session = session;
        currentMessage = new ArrayList<AlarmMessage>();
        dbUtil = new DBUtil();
        currentIndex = 0;//此時是0條訊息
    }

    @Override
    public void run() {
        while (true) {
            List<AlarmMessage> list = null;
            try {
                try {
                    list = dbUtil.getFromDB();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (list != null && currentIndex < list.size()) {
                for (int i = currentIndex; i < list.size(); i++) {
                    try {
                        session.getBasicRemote().sendText(list.get(i).getFanNo()
                                + "," + list.get(i).getTime()
                                + "," + list.get(i).getDescription());
//                            session.getBasicRemote().sendObject(list.get(i)); //No encoder specified for object of class [class AlarmMessage]
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                currentIndex = list.size();
            }
            try {
                //一秒重新整理一次
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

在onopen中啟動傳送資料執行緒

import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocket")
public class websocket {

    @OnOpen
    public void onOpen(Session session){
        OneThread thread =null;
        thread=new OneThread(session);
        thread.start();
    }
}

js實現websocket客戶端

<%@ page import="java.sql.*" %>
<html>
<head>
    <script type="text/javascript">
        //先檢驗能不能執行起來,能不能連上,自動推送資料,先不做資料顯示
        //客戶端就會與伺服器進行連線
        var webSocket = new WebSocket("ws://localhost:8081/websocket");

        //這裡只是除錯用
        //連線失敗時回撥
        webSocket.onerror = function (event) {
            makeDataOnWeb("error");
        };

        //這裡只是除錯用
        //連線成功時回撥,真的會執行括號中的程式碼!
        webSocket.onopen = function (event) {
            makeDataOnWeb("conn success");
        };

        webSocket.onmessage = function (event) {
            makeDataOnWeb(event.data);

        };

        //這裡只是除錯用
        webSocket.onclose = function (event) {
            makeDataOnWeb("conn close");
        };

        function makeDataOnWeb(data) {
            var a = data;
            var divNode = document.getElementById("view");
            var liNode = document.createElement("li");
            liNode.innerHTML = a;
            divNode.appendChild(liNode);
//            divNode.insertBefore(liNode, divNode.children[0]);
            //不能用insertAfter,好像不是這麼用的

            //            var divNode = document.getElementById("view");
//            var trNode = document.createElement("tr");
//            var td1 = document.createElement("td");
//            var td2 = document.createElement("td");
//            var td3 = document.createElement("td");
//            td1.innerHTML = a;
//            td2.innerHTML = a;
//            td3.innerHTML = a;
//            trNode.appendChild(td1)
//            trNode.appendChild(td2)
//            trNode.appendChild(td3)
            //            var head = document.getElementById("head");

//            document.write(a+"<br>");//直接寫
//            document.getElementsById("a").innerHTML="fadfadfa";//不輸出任何內容

        };

    </script>
</head>

<body>

<%@page contentType="text/html; utf8" %>
<%@page language="java" %>
<%@page import="java.sql.*" %>
<%@page pageEncoding="UTF-8" %><!--解決中文亂碼-->

<div id="view">

</div>

</body>

</html>

web執行結果

這裡寫圖片描述