WebSocket implementation of database updates foreground real-time display

Source: Internet
Author: User
Tags apache tomcat

After updating the database with a small instance, push the message to the foreground and let the foreground do the corresponding operation.

Demand

After the database update, the server pushes the message to the foreground and lets the foreground do the operation. (Data for the database is not written by the server)

The implementation of the word is to use polling, because the database data is not inserted through the background of the update, so no matter what method, you need to loop to read the database information or database log files. The difference is whether the front-end polling, or the background polling.

If the use of the foreground polling, is the front desk regularly send requests to the background to update the data, with setinterval () can be achieved. If you look at the network, you can see dozens of or even hundreds of requests in a F12. Because I was also the first to achieve such a function, although there is no research on the performance of this aspect, but see a short period of time so many requests still feel flustered panic.

So think of the use of background polling, the advantage of background polling is that the foreground does not have to send the request to the background, but wait until the background to find the data updated to remind the foreground to re-request data. This will require the use of websocket.

The HTTP connection we normally use is the only client that can send requests to the server.

The most important feature of WebSocket is that the server can actively push information to the client, the client can also actively send information to the server, is a true two-way equality dialogue, belongs to the server push technology.

When querying the data, it is also possible to use the database stored procedures to implement, when storing data, call Java program to notify. (because there are some processing problems not to be achieved)

Environment

Server Version:apache tomcat/7.0.69
Java version:1.7.0_80

Jar packages to be introduced: Tomcat's own Tomcat7-websocket.jar and Websocket-api.jar, which are all two jar packages under the Lib folder of the Tomcat installation directory.

It is important to note that Tomcat needs 7.0. Version 47 and above support JSR-356, specific documents can be viewed

Ideas

When a connection is established, a thread is opened to poll the data in the database, and if the query changes to the data, a message is sent to the WebSocket implementation class, and the implementation class receives the message and pushes the message to the connected user.

(If the data is added through the background, you don't have to be so troublesome, just send the message to the WebSocket implementation class directly in the action class that adds the data)

Client code

This part is relatively simple, is through the URL to establish the WebSocket connection, the protocol name WS is WebSocket. In the Websocket.onmessage () method to connect the received message processing, you can do output can also update the page and so on.

    varWebSocket =NULL; //determine if the current browser supports WebSocket    if(' WebSocket 'inchwindow) {        //establish the connection, where the/websocket is the value in the annotation in the servletWebSocket =NewWebSocket ("ws://localhost:8080/Project name/websocket"); }    Else{alert (' Current browser not support WebSocket '); }    //callback method where the connection error occurredWebsocket.onerror =function() {Console.log ("WebSocket connection error occurred");    }; //callback method for successful connection establishmentWebsocket.onopen =function() {Console.log ("WebSocket Connection succeeded"); }    //callback method for receiving messageWebsocket.onmessage =function(event) {Console.log (event.data); if(event.data== "1") {Console.log ("Data Update"); }    }    //callback method for connection shutdownWebsocket.onclose =function() {Console.log ("WebSocket Connection Off"); }    //listen to the window Shutdown event, when the window is closed, actively to close the WebSocket connection, to prevent the connection has not been disconnected and close the window, the server side will throw an exception. Window.onbeforeunload =function() {closewebsocket (); }    //Close WebSocket Connection    functionClosewebsocket () {websocket.close (); }

Server-side code

A thread is started when the connection is opened, the STOPME () method of the thread is called when the connection is closed, and the thread is terminated. When a message is received, the SendMessage () method is called to send a message to all connected users.

It is important to note that once a connection is established, a session is created, which is different from the session in the request, but can be understood with a similar idea. So when sending a message, you also need to call the session method to send a message to the connected user.

WebSocket session Send text message There are two methods: Getasyncremote () and Getbasicremote (), these two methods I just briefly understand, the former is to send the message asynchronously, the latter is to send the message synchronously. This means that getbasicremote () waits for the last message to be sent to send the next message. If there are errors, I hope you will point out!

In the documentation we see that we can also send a message to the sender of the message directly in the OnMessage () method, or return Txt.touppercase () from the server side, but in this case, Our message is that the line Cheng is given to the WebSocket implementation class, so this method is not necessary.

//Publishing Endpoint WebSocket in a relative path@ServerEndpoint ("/websocket") Public classWebsocketservlet {MyThread thread1=NewMyThread (); Thread Thread=NewThread (THREAD1); //used to store the corresponding Mywebsocket object for each client.     Private StaticCopyonwritearrayset<websocketservlet> Websocketset =NewCopyonwritearrayset<websocketservlet>(); PrivateJavax.websocket.Session session=NULL; /*** @ClassName: OnOpen * @Description: Open connection Operation*/@OnOpen Public voidOnOpen (Session session)throwsioexception{ This. session=session; Websocketset.add ( This);        System.out.println (Websocketset); //open a thread to poll the data in the databaseThread.Start (); }       /*** @ClassName: OnClose * @Description: Connection closed Operation*/@OnClose Public voidOnClose () {THREAD1.STOPME (); Websocketset.remove ( This); }       /*** @ClassName: OnMessage * @Description: Send a message to the server informing the database of changes*/@OnMessage Public voidOnMessage (intcount) {System.out.println ("Changed" +count); Try{sendMessage (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }     /*** @ClassName: OnError * @Description: Error action*/@OnError Public voidonError (throwable error) {System.out.println (error);    Error.printstacktrace (); }        /*** This method is not the same as the above methods.     Without annotations, it is based on the method you need to add. * @throwsIOException * Send a custom signal, "1" means to tell the foreground, the database has changed, need to refresh*/     Public voidSendMessage ()throwsioexception{//Mass Message         for(Websocketservlet item:websocketset) {item.session.getBasicRemote (). SendText ("1"); }    }}

Definition of Thread

The line enters upgradeable queries the data in the database once, there is a sum variable, and then the data in the database is polled, new_sum and sum are different, send a message to the WebSocket implementation class.

 Public classMyThreadImplementsrunnable{Private intsum; Private intnew_sum; Private BooleanSTOPME =true;  Public voidStopme () {STOPME=false; }      /*(non-javadoc) * @see Java.lang.runnable#run ()*/     Public voidrun () {Urldao Urldao=NewUrldao (); Sum=Urldao.selectcount (); Websocketservlet WBS=NewWebsocketservlet ();  while(STOPME) {new_sum=Urldao.selectcount (); if(sum!=new_sum) {System.out.println ("Change"); Sum=new_sum;            Wbs.onmessage (sum); }            Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }    }}

Test

At this point my demand is probably complete, because it is the first time to write WebSocket and thread-related instances, if there is a problem I hope you can say!

WebSocket implementation of database updates foreground real-time display

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.