WebSocket, simple understanding is the H5 comes with a set of socket API, use it to achieve the client and the service side of the long connection.
Use case: To achieve a real-time report of the activity, that is, graphic live function
- First look at the structure of the project, very simple, two classes
Mywebsocket.java
This is the service side of the socket, just add the appropriate annotations to the function, note the annotation on the class name @serverendpoint ("/websocket"), this/websocket is like a servlet URL configured in Web. Xml.
The H5 client interacts with this service-side implementation information
PackageWebsocket.server;ImportJava.io.IOException;ImportJava.util.concurrent.CopyOnWriteArraySet;ImportJavax.websocket.OnClose;ImportJavax.websocket.OnError;ImportJavax.websocket.OnMessage;ImportJavax.websocket.OnOpen;ImportJavax.websocket.Session;ImportJavax.websocket.server.ServerEndpoint;the annotation is used to specify a URI that the client can use to connect to WebSocket. A servlet-like annotation mapping. No need to configure in Web. Xml. @ServerEndpoint("/websocket") Public class mywebsocket { //static variable to record the current number of online connections. It should be designed to be thread-safe. Private Static intOnlinecount =0;The thread-safe set of the//concurrent package is used to store the corresponding Mywebsocket object for each client. To enable the server to communicate with a single client, you can use a map to store it, where key can identify the user Private StaticCopyonwritearrayset<mywebsocket> Websocketset =NewCopyonwritearrayset<mywebsocket> ();//Connection session with a client, which is required to send data to the client PrivateSession session;/** * Connection established method of successful call * * @param session * Optional Parameters. Session is a connection to a client, it needs to send data to the client * @throws IOException */ @OnOpen Public void OnOpen(Session session)throwsIOException { This. session = Session; Websocketset.add ( This);//Add in SetAddonlinecount ();//Online number plus 1System.out.println ("There are new connections to join!" The current number of people online is "+ Getonlinecount ());//Simulate extracting historical information from the database This. SendMessage ("); This. SendMessage ("This is the first live picture, apron. gif"); This. SendMessage ("); This. SendMessage ("); This. SendMessage ("This is the second picture, oh ..."); This. SendMessage ("<br/>"); This. SendMessage ("---------------------------above is historical information---------------------------<br/>"); }/** * Method of connection Shutdown call * / @OnClose Public void OnClose() {Websocketset.remove ( This);//Remove from setSubonlinecount ();//Online number minus 1System.out.println ("There's a connection off!" The current number of people online is "+ Getonlinecount ()); }/** * The method called after receiving the client message * * @param message * The client sends over messages * @param session * Optional Parameters * / @OnMessage Public void OnMessage(String message, session session) {System.out.println ("Message from the client:"+ message);//Mass message for(Mywebsocket Item:websocketset) {Try{Item.sendmessage (");//Simulate uploaded imagesItem.sendmessage (message); }Catch(IOException e) {E.printstacktrace ();Continue; } } }/** * Called when an error occurs * * @param session * @param Error */ @OnError Public void OnError(Session session, throwable error) {System.out.println ("Error occurred"); Error.printstacktrace (); }/** * Send Message to client * * @param message * @throws ioexception */ Public void SendMessage(String message)throwsIOException { This. Session.getbasicremote (). SendText (message);//This.session.getAsyncRemote (). SendText (message);} Public Static synchronized int Getonlinecount() {returnOnlinecount; } Public Static synchronized void Addonlinecount() {mywebsocket.onlinecount++; } Public Static synchronized void Subonlinecount() {mywebsocket.onlinecount--; }}
Liveservlet.java
This is used to unify the entrance, that is, the user through the unique path http://localhost/websocket into the live
PackageWebsocket.servlet;ImportJava.io.IOException;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public class liveservlet extends httpservlet{ @Override protected void Doget(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException {//TODO auto-generated method stub Super. DoPost (req, resp); }@Override protected void DoPost(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException {//TODO auto-generated method stubString method = Req.getparameter ("Method");if("Tolive". Equals (method)) {Req.getrequestdispatcher ("/web-inf/jsp/client.jsp"). Forward (req, resp); }Else if("Fabu". Equals (method)) {//Here to implement the file upload to return the image URL to the client, the client sends this URL to the WebSocket server, there should be code ... Please, Brain tonic .} }}
Service side is so simple implementation of the next, specific according to their business logic processing, and then to see the client
<%@ page language="java" import="java.util.*" pageencoding= "UTF-8"%><% String path = request. Getcontextpath (); String basepath = request. Getscheme () + "://" + request. getServerName () + ": + request. Getserverport () + path + "/";%><! DOCTYPE html><html><head><base href="<%=basePath%>"><title>Client WebSocket</title><script type="text/javascript"src="http://file.iqilu.com/ Custom/new/public/js/jquery-1.8.1.min.js "> </script><script>$ (document). Ready (function() { }); function load() { $ (". Content"). Hide (); }</script><style type="Text/css"> img { width: + px; Height: + px}</style></head><body onload="Load ()"> <br /> <br /> <p class="Tip" style="color: #fe1234">Getting into the graphic live ...</P> <div class="Content"> <div id="message"></div> <p>Come and publish your live map ~</P> <br /> <br /> <form Action="Http://localhost/websocket/liveservlet?method=fabu"method ="POST"> <input type="file" value="Please select Picture" /><button onclick="UploadFile ()">Upload image</button> <input id="comment" type="text" value="A short description of the paragraph" /><br /> </form> <button onclick="Send ()">Release</button> <button onclick="Closewebsocket ()">Exit Live</button> </div></body><script type="Text/javascript"> varWebSocket =NULL;//Determine if the current browser supports WebSocket if(' WebSocket ' inchwindow) {WebSocket =NewWebSocket ("Ws://localhost/websocket/websocket"); }Else{Alert (' not support WebSocket ') }//Connection Error callback methodWebsocket.onerror = function() {Setmessageinnerhtml ("Error"); };//Connection successfully established callback methodWebsocket.onopen = function(event) {$(". Content"). Show (); $(". Tip"). Text ("2016XXXX Online Summit Live"); }//The callback method that receives the messageWebsocket.onmessage = function(event) {Setmessageinnerhtml (Event.data); }//Connection shutdown callback methodWebsocket.onclose = function() {Setmessageinnerhtml ("Close"); }//Monitoring 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() {Websocket.close (); }//Display messages on a Web page function setmessageinnerhtml(InnerHTML) {document.getElementById (' message '). InnerHTML + = InnerHTML +' <br/> '; }//Close connection function closewebsocket() {Websocket.close (); }//Send Message function send() { varMessage = document.getElementById (' comment '). Value; Websocket.send (message); }</script></html>
Interaction is basically like this, the case is clear, the code is simple, you can quickly get started on WebSocket
Project source download (to receive a point points oh, make points to raise the pressure lattice [laughter])
Using WebSocket to realize the graphic live function