WebSocket instance (show file import processing progress)

Source: Internet
Author: User
Tags log log

When you import large quantities of data, you need to immediately display the progress of processing the files. Consider that Ajax polling is too wasteful for resources to be implemented using WebSocket.

The project uses spring MVC (3.1), which is combined with WebSocket to require version 4.0 or more. Therefore, the websocket provided by spring is not used.

1. Depending on Tomcat 7 or Java EE 7

MAVEN Import:

<!--webscoket Start-to-        <dependency>            <groupId>org.apache.tomcat</groupId>            <artifactId>tomcat-websocket-api</artifactId>            <version>7.0.47</version>            < scope>provided</scope>        </dependency>        <dependency>            <groupid>javax</ groupid>            <artifactId>javaee-api</artifactId>            <version>7.0</version>            <scope>provided</scope>        </dependency>        <dependency>            <groupId> org.java-websocket</groupid>            <artifactId>Java-WebSocket</artifactId>            <version >1.3.0</version>        </dependency><!--webscoket End---

2. Service-side

Tool classes, storing unique keys and connections

ImportJava.util.Map;ImportJava.util.concurrent.ConcurrentHashMap;Importjavax.websocket.Session; Public classWebsocketsessionutils { Public Staticmap<string, session> clients =NewConcurrenthashmap<>();  Public Static voidput (String Batchkey, session session) {Clients.put (Batchkey, session); }     Public StaticSession Get (String batchkey) {returnClients.get (Batchkey); }     Public Static voidRemove (String batchkey) {clients.remove (Batchkey); }     Public Static Booleanhasconnection (String batchkey) {returnClients.containskey (Batchkey); }}

WebSocket processing classes, do not add business logic

Importjavax.websocket.*;ImportJavax.websocket.server.PathParam;ImportJavax.websocket.server.ServerEndpoint;ImportOrg.apache.commons.logging.Log;Importorg.apache.commons.logging.LogFactory; @ServerEndpoint ("/websocket.ws/{batchkey}") Public classWebsocketendpoint {Private StaticLog log = Logfactory.getlog (websocketendpoint.class); @OnOpen Public voidOnOpen (@PathParam ("Batchkey"String Batchkey, session session) {Log.info ("Websocket Start connecting:" +Batchkey);    Websocketsessionutils.put (Batchkey, session); } @OnMessage PublicString OnMessage (@PathParam ("Batchkey") string Batchkey, String message) {return"Got Your message (" + Message + "). Thanks! "; } @OnError Public voidOnError (@PathParam ("Batchkey") String Batchkey, Throwable Throwable, session session) {Log.info ("Websocket Connection Exception:" +Batchkey);        Log.info (Throwable.getmessage (), throwable);    Websocketsessionutils.remove (Batchkey); } @OnClose Public voidOnClose (@PathParam ("Batchkey"String Batchkey, session session) {Log.info ("Websocket Close Connection:" +Batchkey);    Websocketsessionutils.remove (Batchkey); }}

3. Client

Using JS closure package WebSocket, import websocket.js

varMywebsocket = (function() {    varMysocket = {}; Mysocket.trytime= 0; Mysocket.websocketurl=NULL; Mysocket.batchkey=NULL; Mysocket.websocket=NULL; Mysocket.initsocket=function() {        if(!window. WebSocket) {//alert ("Your browsers don ' t support WebSocket.");            return false; } mysocket.websocket=NewWebSocket (Mysocket.websocketurl +Mysocket.batchkey); MySocket.webSocket.onmessage=function(msg) {Console.log (msg);        }; MySocket.webSocket.onerror=function(event) {Console.log (event);        }; MySocket.webSocket.onopen=function(event) {Console.log (event);        }; MySocket.webSocket.onclose=function() {            if(Mysocket.trytime < 10) {setTimeout (function() {WebSocket=NULL; Mysocket.trytime++;                Mysocket.initsocket (); }, 500); } Else{mysocket.trytime= 0;    }        };    }; Mysocket.closesocket=function() {        if(mysocket.websocket) {mySocket.webSocket.close ();    }    }; returnMysocket;}) ();

Start WebSocket when Ajax executes, using timestamp as the unique key.

var commissionwebsocketurl = "ws://${remote_websocket}/commission/websocket.ws/";

        vartimestamp=NewDate (). GetTime (); $.ajax ({type:"POST", Url:trialurl+ "? batchkey=" +timestamp, data: $ ("#batchUploadForm"). Serialize (), DataType:"HTML", Beforesend:function(XHR) {varCountdiv = $ (' #loading #countDiv '); if(countdiv.length==0) {Countdiv=$ ("<div id= ' Countdiv ' ></span>"); $(' #loading '). Append (Countdiv); }                $(' #loading '). Show (); Mywebsocket.websocketurl=Commissionwebsocketurl; Mywebsocket.batchkey=timestamp;                Mywebsocket.initsocket (); MyWebSocket.webSocket.onmessage=function(msg) {countdiv.html ("Mtusker is processing date,please wait ... "+msg.data);            }; }, Complete:function(){                $(' #loading '). Hide ();            Mywebsocket.closesocket (); }, Success:function(data) {$ ("#trialInfoPopup"). HTML (data); Mydialog= $ ("#trialInfoPopup"). dialog ({position: [' Center ', width:1400,height:600, modal:true, Title:"Batch Upload Trial"                }); }        });

Java Project as Client

Importjava.io.IOException;ImportJavax.websocket.ClientEndpoint;ImportJavax.websocket.OnError;ImportJavax.websocket.OnMessage;ImportJavax.websocket.OnOpen;Importjavax.websocket.Session; @ClientEndpoint Public classwebsocketclient {@OnOpen Public voidOnOpen (Session session) {SYSTEM.OUT.PRINTLN ("Connected to Endpoint:" +session.getbasicremote ()); Try{session.getbasicremote (). SendText ("Hello"); } Catch(IOException ex) {}} @OnMessage Public voidonMessage (String message) {SYSTEM.OUT.PRINTLN (message); } @OnError Public voidOnError (Throwable t) {t.printstacktrace (); }}
Importjava.io.IOException;ImportJava.net.URI;ImportJavax.websocket.ContainerProvider;Importjavax.websocket.DeploymentException;Importjavax.websocket.Session;ImportJavax.websocket.WebSocketContainer; Public classWebsocketapp {Private StaticString webUrl = "localhost";  Public Static voidSend (String batchkey, String message) {Websocketcontainer container=Containerprovider.getwebsocketcontainer (); String URI= "ws://" +weburl+ "/websocket.ws/" +Batchkey; System.out.println ("Connecting to" +URI); Try{Session Session=Websocketsessionutils.get (Batchkey); if(Session = =NULL) {Session= Container.connecttoserver (websocketclient.class, Uri.create (URI));            Websocketsessionutils.put (Batchkey, session);        } session.getbasicremote (). SendText (message); } Catch(deploymentexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }    }     Public StaticString Getweburl () {returnWebUrl; }     Public Static voidSetweburl (String webUrl) {Websocketapp.weburl=WebUrl; }        }

The Import file Processing section, as a Java project client, calls WebSocket during processing

                int num = 0;                  for (map<string,string> rowinfo:rows) {                        websocketapp.send (batchkey, num+ + "/" + rows.size ()); c12/> ...                       }

This enables instant processing progress to be sent during the processing of the file.

Note: When using HTTPS, you need to change

var commissionwebsocketurl = "wss://${remote_websocket}/commission/websocket.ws/";

WebSocket instance (show file import processing progress)

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.