WebSocket update MySQL data to the page in real time

Source: Internet
Author: User

The original intention of using WebSocket is to update the alarm information in MySQL to the Web page display in real time.
Not how to touch the Web, the code is really rotten, but also is a function of implementation, put here is also spur themselves, the web will be more effort

Get ready

Introducing Dependencies

    <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>

First look at the format of the data in MySQL

Data encapsulation

 Public classAlarmmessage {PrivateString Fanno;PrivateString time;PrivateString description; Public Alarmmessage(String Fanno, String time, string description) { This. Fanno = Fanno; This. Time = time; This. Description = description; } PublicStringGetfanno() {returnFanno; } PublicStringGetTime() {returnTime } PublicStringgetdescription() {returnDescription }}

JDBC reads data from the database

 PublicClass Dbutil { Public List<Alarmmessage>Getfromdb () throws SQLException, ClassNotFoundException, Illegalaccessexception, instantiationexception {List<Alarmmessage> List=NewArrayList<Alarmmessage>();StringDirver="Com.mysql.jdbc.Driver";StringUser="Root";StringPsd="Root";StringDatabase="Streamingproblem";StringTableName="Problem";StringUrl="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 ();StringSql="SELECT * from"+TableNameResultSetRs=Stat.ExecuteQuery (SQL); while(RS.Next ()) {Alarmmessage alarmmessage=NewAlarmmessage (RS.GetString (2), RS.GetString (3), RS.GetString (4));List.Add (Alarmmessage); } RS.Close (); Stat.Close (); Conn.Close ();return List; }}
Start writing WebSocket

Write a thread to send new data to the page, run to open an infinite loop, with a variable currentindex record the current amount of data, when there is new data, send new data

ImportJavax.websocket.Session; Public  class onethread extends Thread {    PrivateSession session;PrivateList<alarmmessage> Currentmessage;PrivateDbutil Dbutil;Private intCurrentindex; Public Onethread(Session session) { This. session = Session; Currentmessage =NewArraylist<alarmmessage> (); Dbutil =NewDbutil (); Currentindex =0;//This is 0 messages}@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(inti = 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 C Lass [Class Alarmmessage]}Catch(IOException e)                    {E.printstacktrace ();            }} Currentindex = List.size (); }Try{//One second to refresh onceThread.Sleep ( +); }Catch(Interruptedexception e)            {E.printstacktrace (); }        }    }}

To start the Send data thread in OnOpen

import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;@ServerEndpoint("/websocket")publicclass websocket {    @OnOpen    publicvoidonOpen(Session session){        OneThread thread =null;        thread=new OneThread(session);        thread.start();    }}
JS Implementation WebSocket Client
<%@ page import="java.sql.*" %><html><head>    <script type="Text/javascript">        //test can be run up, can not connect, automatically push data, do not do the data display        //client will connect to the server        varWebSocket =NewWebSocket ("Ws://localhost:8081/websocket");//This is just for debugging        //callback when connection failsWebsocket.onerror = function (event) {Makedataonweb ("Error"); };//This is just for debugging        //When the connection succeeds, the code in parentheses is really executed! Websocket.onopen = function (event) {Makedataonweb ("Conn Success");        }; Websocket.onmessage = function (event) {Makedataonweb (Event.data); };//This is just for debuggingWebsocket.onclose = function (event) {Makedataonweb ("Conn Close"); }; function makedataonweb(data) {            varA = data;varDivnode = document.getElementById ("View");varLiNode = Document.createelement ("Li");            linode.innerhtml = A; Divnode.appendchild (LiNode);//Divnode.insertbefore (LiNode, divnode.children[0]);            //can't use InsertAfter, it doesn't seem to work that way.            //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>");//Direct Write//Document.getelementsbyid ("a"). Innerhtml= "FADFADFA";//do not output any content};</script></head><body><% @page contenttype="text/html; UTF8 " %><% @page language="java" %><% @page import="java.sql.*" %><% @page pageencoding="UTF-8" %><!--solve Chinese characters --<div id="View"></div></body></html>
Web Run Results

WebSocket update MySQL data to the page in real time

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.