WebSocket 即時更新mysql資料到頁面

來源:互聯網
上載者:User

標籤:cli   檢驗   spec   javaee   nod   desc   api   更新   引入   

使用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運行結果

WebSocket 即時更新mysql資料到頁面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.