Original address: http://www.ibm.com/developerworks/cn/java/j-lo-WebSocket/
WebSocket Past Life
As we all know, the interactive process of WEB application is usually the client sends a request through the browser, the server side receives the request to process and returns the result to the client, the client browser presents the information, this mechanism is not very frequent for the information change application is fair, but for the real-time requirements of high, Huge concurrency of applications, especially in the current trend of mobile Internet development, high concurrency and user real-time response is a common problem of WEB applications, such as real-time information on financial securities, geographical access in Web navigation applications, social network real-time message push and so on.
The traditional request-response pattern of Web development in the processing of such business scenarios, usually the use of real-time communication solutions, common is:
- Polling, the principle is simple to understand, is the client through a certain time interval in a frequent request to the server to send requests to maintain client and server side of the data synchronization. The problem is obvious, when the client sends the request to the server side at a fixed frequency, the server-side data may not be updated, resulting in a lot of unnecessary requests, wasting bandwidth and inefficiency.
- Based on the Flash,adobeflash through its own Socket implementation of the data exchange, and then use Flash to expose the corresponding interface for JavaScript calls, so as to achieve real-time transmission purposes. This method is more efficient than polling, and because of the high flash installation rate, the application scenario is wide, but the support of flash on the mobile Internet terminal is not good. There is no flash in the IOS system, although there is flash support in Android, but the actual effect is not satisfactory, and the hardware configuration of mobile devices requires a high. In 2012, Adobe officially announced that it would no longer support the android4.1+ system, announcing the death of Flash on mobile devices.
As can be seen from the above, the traditional Web mode in dealing with high concurrency and real-time requirements, will encounter insurmountable bottlenecks, we need an efficient and energy-saving bidirectional communication mechanism to ensure the real-time transmission of data. In this context, the WebSocket, which is based on the HTML5 specification, is called the Web TCP.
Early HTML5 did not form the industry uniform norms, the browser and application server vendors have different similar implementations, such as IBM's Mqtt,comet Open source framework, until 2014, HTML5 in IBM, Microsoft, Google and other giants of the promotion and collaboration finally dust landed, formally From the draft to the actual standard specification, the application server and browser vendors gradually began to unify, in JavaEE7 also implemented the WebSocket protocol, so whether the client or the server WebSocket are complete, readers can consult HTML5 specifications, familiar with the new HTML Protocol specification and WebSocket support.
WebSocket mechanism
The following is a brief introduction to the principle and operating mechanism of WebSocket.
WebSocket is a new protocol for HTML5. It realizes the browser and the server full-duplex communication, can better save the server resources and bandwidth and achieve real-time communication, it is based on TCP, the same as HTTP through TCP to transfer data, but it and HTTP the maximum difference is:
- WebSocket is a two-way communication protocol, after establishing the connection, both the WebSocket server and the Browser/client Agent can send or receive data to each other proactively, just like a Socket.
- WebSocket requires a TCP-like client and server-side handshake connection to communicate with each other after a successful connection.
The non-WebSocket mode traditional HTTP client interacts with the server as shown:
Figure 1. Traditional HTTP Request Response Client Server interaction diagram
Using the WebSocket mode client interacts with the server such as:
Figure 2.WebSocket Request Response Client Server interaction diagram
Compared to the traditional HTTP each request-response requires the client and the server to establish a connection mode, WebSocket is similar to the Socket TCP Long connection communication mode, once the WebSocket connection is established, the subsequent data are transmitted in the form of a frame sequence. The client and the server are not required to re-initiate the connection request before the client disconnects the WebSocket connection or the servers end the connection. In the case of large amount of concurrency and high client-server interaction load, the consumption of network bandwidth resources is greatly saved, and the performance advantage is obvious, and the client sends and receives messages on the same persistent connection, and the real-time advantage is obvious.
We'll look at the difference between the WebSocket communication and the traditional HTTP via the client-side and service-end messages:
On the client side, new WebSocket instantiates a newer WebSocket client object that connects a server like Ws://yourdomain:port/path WebSocket url,websocket client object that is automatically parsed and recognized as The WebSocket request, thereby connecting the server port, performs both handshake processes, and the client sends data in a similar format:
Listing 1.WebSocket Client Connection messages
http://localhost
: 8080sec-websocket-version:13
As you can see, the client-initiated WebSocket connection message is similar to the traditional HTTP message, and the "upgrade:websocket" parameter value indicates that this is a WebSocket type request, and "Sec-websocket-key" is WebSocket A base64 encoded ciphertext sent by the client requires the server to return a corresponding encrypted "sec-websocket-accept" answer, otherwise the client throws an "error during WebSocket handshake" fault and closes the connection.
The data format returned by the server after receiving the message is similar:
Listing 2.WebSocket Service-side response messages
http/1.1 101 Switching protocolsupgrade:websocketconnection:upgradesec-websocket-accept:k7djldlooiwig/ mopvwfb3y3fe8=
The value of "Sec-websocket-accept" is returned to the client after the server is computed with a client-consistent key, and "http/1.1 101 switching Protocols" indicates that the server accepts a client connection to the WebSocket protocol, After such a request-response processing, the client service side of the WebSocket connection handshake succeeds, the subsequent TCP communication can be made. Readers can refer to the WebSocket protocol stack for a more detailed interactive data format between the WebSocket client and the server.
In terms of development, the WebSocket API is also very simple, we only need to instantiate the WebSocket, create the connection, and then the server and the client can send and respond to each other message, in the following WebSocket implementation and Case Analysis section, you can see the detailed WebSocket API and code implementation.
WebSocket implementation
As mentioned above, the implementation of WebSocket is divided into two parts of the client and the server, the client (usually the browser) sends the WebSocket connection request, the service side responds, implements the action similar to the TCP handshake, thus forms an HTTP between the browser client and the WebSocket server. Long connection Fast channel. The subsequent direct data transfer between the two is no longer necessary to initiate a connection and corresponding.
The following is a brief description of the WebSocket Server API and client API.
WebSocket Service-side API
The WebSocket server has been largely supported by the JEE JSR356 standard API (see JSR356 WebSocket API Specification) in various mainstream application server vendors, and the following lists some common commercial and open source application servers for WebSocket Serv Er-side Support situation:
Table 1.WebSocket Service-side support
manufacturer |
Application Server |
Notes |
Ibm |
Websphere |
WebSphere version 8.0 and above support, prior to 7.X with MQTT support similar HTTP long connection |
Oracle |
Weblogic |
WebLogic 12c Support, 11g and 10g versions support similar HTTP long connections via HTTP Publish |
Microsoft |
Iis |
IIS 7.0+ Support |
Apache |
Tomcat |
Tomcat 7.0.5+ Support, 7.0.2X and 7.0.3X support via custom API |
|
Jetty |
Jetty 7.0+ Support |
Below we use the Tomcat7.0.5 version of the server-side sample code to illustrate the implementation of the WebSocket server:
The JSR356 WebSocket specification uses the javax.websocket.* API, which allows a common Java object (POJO) to use @ServerEndpoint annotations as the endpoint of the WebSocket server, with the following code examples:
Listing 3.WebSocket server-side API Example
@ServerEndpoint ("/echo") public class Echoendpoint {@OnOpen public void OnOpen (Session session) throws IOException {//below Code omitted ...} @OnMessage public string OnMessage (String message) {//The following code is omitted ...} @Message (maxmessagesize=6) public void ReceiveMessage ( String s) {//The following code omitted ...} @OnError public void OnError (Throwable t) {//The following code is omitted ...} @OnClose public void OnClose (session session, Closereason reason) {//The following code omitted ...} }
Code Explanation:
The simple code above establishes a WebSocket server, and the annotation annotation endpoint of the @ServerEndpoint ("/echo") indicates that the WebSocket server is running on the Ws://[server IP or domain name]:[serve R Port]/websockets/echo's access endpoint, the client browser has been able to initiate an HTTP long connection to the WebSocket client API.
A class that uses serverendpoint annotations must have a common parameterless constructor, and the Java method that @onMessage annotations is used to receive incoming WebSocket information, either in text format or in binary format.
OnOpen is called when a new connection is established at this endpoint. Parameters provide more detail at the other end of the connection. The Session indicates that the other end of the two WebSocket endpoint conversation connection can be understood as a concept similar to HTTPSession.
The OnClose is called when the connection is terminated. The parameter Closereason can encapsulate more details, such as why a WebSocket connection is off.
More advanced customizations such as @Message annotations, the MaxMessageSize property can be used to define the maximum message byte limit, and in the example program, if more than 6 bytes of information is received, the error is reported and the connection is closed.
Note: The WebSocket methods that are supported by different application servers in the early stages are not the same, even if the same vendor, different versions have subtle differences, such as the TOMCAT server 7.0.5 the above version is the standard JSR356 specification implementation, and the 7.0.2x/7.0.3x version uses the custom API ( Websocketservlet and Streaminbound, the former is a container used to initialize the WebSocket environment, which is used to specifically process WebSocket requests and responses, as described in the Case Analysis section, and tomcat7.0.3x and 7.0.2x The Createwebsocketinbound method is defined differently, adding a httpservletrequest parameter that allows more WebSocket client information to be obtained from the request parameter, as shown in the following code:
Listing 4.tomcat7.0.3x version WebSocket API
public class Echoservlet extends Websocketservlet {@Overrideprotected streaminbound createwebsocketinbound (String Subprotocol,httpservletrequest request) {//The following code omitted .... return new Messageinbound () {//The following code omitted ....} protected void Onbinarymessage (Bytebuffer buffer) throws IOException {//The following code omitted ...} protected void Ontextmessage (Charbuffer buffer) throws IOException {Getwsoutbound (). writetextmessage (buffer);// The following code omits ...}};}}
So choosing the Server side of WebSocket needs to choose its version, typically, the updated version of WebSocket support is the standard JSR specification API, but also to consider the development of ease of use and the old version of the program portability, and other aspects of the problem, as described in the following article of the customer case, This is because the client requires a unified Application Server version, so the Websocketservlet implementation of the Tomcat 7.0.3X version is used instead of the JSR356 @ServerEndpoint comment endpoint.
WebSocket Client API
For WebSocket clients, mainstream browsers (including PCs and mobile terminals) now support the standard HTML5 WebSocket API, which means that the client's WebSocket javascirpt scripts have good consistency and cross-platform features, and the following lists common Browser vendor support for WebSocket:
Table 2.WebSocket Client Support
Browser |
Support Situation |
Chrome |
Chrome version 4+ support |
Firefox |
Firefox version 5+ support |
Ie |
IE version + + support |
Safari |
IOS 5+ Support |
Android Brower |
Android 4.5+ Support |
The client WebSocket API is basically unified across mainstream browser vendors, so use the JavaScript API of the WebSocket client defined by the standard HTML5, and of course use the industry's open source framework that meets the WebSocket standard specification. such as Socket.io.
The following is a code example that illustrates the client implementation of WebSocket:
Listing 5.WebSocket Client API sample
var ws = new WebSocket ("ws://echo.websocket.org"); Ws.onopen = function () {ws.send ("test!");}; Ws.onmessage = function (evt) {console.log (evt.data); Ws.close ();}; Ws.onclose = function (evt) {console.log ("websocketclosed!");}; Ws.onerror = function (evt) {console.log ("websocketerror!");};
The first line of code is to request a WebSocket object, the parameter is the server-side address that needs to be connected, as the HTTP protocol begins, the URL of the WebSocket protocol uses ws://, and the security WebSocket protocol starts with wss://.
The second line to the fifth behavior WebSocket object Registration Message handler function, WebSocket object support four messages OnOpen, OnMessage, OnClose and OnError, with these 4 events, we can easily and easily navigate Websock Et.
When the Browser and Websocketserver connection succeeds, the OnOpen message is triggered, and if the connection fails, the sending, receiving data fails, or the processing data is faulty, Browser triggers the onerror message; when Browser receives WebSocketS The onmessage message is triggered when the data is sent by erver, and the parameter evt contains the data transmitted by the Server, and the OnClose message is triggered when Browser receives a close connection request sent by the Websocketserver side. We can see that all operations are triggered in the form of an asynchronous callback, which does not block the UI, allows for faster response times, and a better user experience.
WebSocket Case Study
Below we have a real customer case to analyze the advantages of WebSocket and specific development implementation (in order to protect customer privacy, the following description eliminates the customer name, the specific business details of the code in the text is no longer described).
Case Introduction
The customer is a mobile device manufacturer, the mobile device is loaded with the Android/ios operating system, the device is divided into two categories (hereinafter referred to as a, b two categories), a class of equipment at any time in the mobile state, Class B equipment for a class of equipment management control equipment, customers need to see in class B equipment at any time the geographical location of Class A Information and status information. such as Class A equipment on-line, when offline, class B equipment needs to be notified immediately, Class A equipment reported, Class B equipment also need to be in real-time to escalate a Class A device location information.
In order to reduce the difficulty of the cross-platform and the implementation of the workload, customers consider the lightweight Web App to screen the difference of Android/ios platform, a class of equipment, and in the operating state of a-type equipment in the irregular movement state, and class B devices on the status of a class of equipment, the real-time requirements are very high (s Level).
According to the above requirements, A/b device information is stored in the background database, the interaction of A/b device involves frequent and high concurrent requests from the Web client/server-correspondingly, if the traditional HTTP request-response mode is used, the service needs to be polled on the web App of class B devices. It is bound to bring a large load pressure on the server, and when class A equipment is not on-line or reported activities such as events, class B equipment polling a serious waste of network resources.
Solution Solutions
In summary, the project uses WebSocket technology to realize real-time message notification and push, whenever A class device/class B device Online login success is open WebSocket HTTP long connection, new class A device on-line, location change, offline and other status changes through WebSocket send real-time messages , the WebSocket Server handles real-time messages for class A devices and pushes them in real time to the subordinate class B devices.
The WebSocket client uses jquery Mobile (jquery Mobile development is no longer described in detail in this article, and interested readers can refer to the jquery Mobile introduction), using the native WebSocket API to interact with the server.
The service side follows the client's existing application Server Tomcat 7.0.33 version, using the Apache custom API to implement the WebSocket server side, generate a WebSocket HTTP long connection for an on-line Class A device, whenever a Class A device is online , location update, offline and other events, the client sends a text message, the server identifies and processes, sends a real-time message to the Class B device, and the Class B device client receives the message, identifies the corresponding event of Class A device, and completes the corresponding class A device location refresh and other business operations.
It involves the class A device, class B device and background server interaction timing diagram as follows:
Figure 3:a/b Class device WebSocket interaction diagram
The WebSocket client for A/b devices is encapsulated in Websocket.js's JavaScript code, packaged with the JQuery Mobileapp as a mobile Apk/ipa installation package; WebSocket server implementations are primarily Websock Etdeviceservlet.java, Websocketdeviceinbound.java,websocketdeviceinboundpool.java several classes. Here we describe the specific code implementation.
Code implementation
In the following section we explain the main code implementations in this case, and the reader can download the complete code listing to learn more.
Websocketdeviceservlet class
When a class A device or class B device initiates a WebSocket long connection, the server accepts the request Websocketdeviceservlet class, unlike the traditional HttpServlet, Websocketdeviceservlet class implements Createw Ebsocketinbound method, similar to Socketserver's Accept method, the new production Websocketinbound instance corresponds to the client HTTP long connection, processing and client interaction function.
Examples of Websocketdeviceservlet service-side code are:
Listing 6.websocketdeviceservlet.java code example
public class Websocketdeviceservlet extends Org.apache.catalina.websocket.WebSocketServlet {private static final long Serialversionuid = 1L; @Override protected Streaminbound createwebsocketinbound (String subprotocol,httpservletrequest request) { Websocketdeviceinbound newclientconn = new Websocketdeviceinbound (request); Websocketdeviceinboundpool.addmessageinbound (Newclientconn); return newclientconn;} }
Code Explanation:
Websocketservlet is the background listening process for the WebSocket protocol, and like traditional HTTP requests, websocketservlet is similar to the Servlet listener process in spring/struct, except that the client WS prefix specifies its The listening protocol is WebSocket.
Websocketdeviceinboundpool implements a client-side WebSocket connection pooling function similar to the JDBC database connection pool, and unifies the WebSocket server's message push for a single client/multiple clients (same group class A device), as described in Websocketdeviceinboundpool code class explanation.
Websocketdeviceinboundl class
Websocketdeviceinbound class for each class A and B device authentication after login, the client establishes the HTTP long connection of the corresponding background service class, similar to socket programming in the Socketserver accept after the socket process, in the WebS The Ocketinbound receives the real-time location information sent by the client, and sends the subordinate class A device real-time location information and the location analysis result data to the client (class B device), and the input stream and output stream are all customized by the WebSocket protocol. Wsoutbound is responsible for the output, Streaminbound and Wsinputstream are responsible for receiving data:
Listing 7.websocketdeviceinbound.java Class code example
public class Websocketdeviceinbound extends Messageinbound {private final httpservletrequest request;private Deviceaccount connecteddevice;public deviceaccount Getconnecteddevice () {return connecteddevice;} public void Setconnecteddevice (Deviceaccount connecteddevice) {this.connecteddevice = Connecteddevice;} Public HttpServletRequest Getrequest () {return request;} Public Websocketdeviceinbound (HttpServletRequest request) {this.request = Request;deviceaccount Connectedda = ( Deviceaccount) Request.getsession (True). getattribute ("Connecteddevice"); if (connectedda==null) {String deviceId = Request.getparameter ("id");D eviceaccountdao Devicedao = new Deviceaccountdao (); Connectedda = Devicedao.getdabyid ( Integer.parseint (DeviceId));} This.setconnecteddevice (Connectedda);} @Overrideprotected void OnOpen (Wsoutbound outbound) {/} @Overrideprotected void onClose (int status) { Websocketdeviceinboundpool.removemessageinbound (this);} @Overrideprotected void Onbinarymessage (Bytebuffer message) throws Ioexception {throw new unsupportedoperationexception ("Binary Message not supported."); @Overrideprotected void Ontextmessage (Charbuffer message) throws IOException { Websocketdeviceinboundpool.processtextmessage (this, message.tostring ());} public void SendMessage (BaseEvent event) {String eventstr = json.tojsonstring (event); try {this.getwsoutbound (). Writetextmessage (Charbuffer.wrap (EVENTSTR)); The following code omits} catch (IOException e) {e.printstacktrace ();}}}
Code Explanation:
Connecteddevice is an instance of A/B class client device class that is currently connected, where it is a member variable for subsequent processing interactions.
The SendMessage function sends data to the client, uses the Websocket wsoutbound output to flow to the client push the data, and the data format is JSON-Unified.
The Ontextmessage function triggers an event when the client sends a message to the server, calls Websocketdeviceinboundpool's processtextmessage to unify the login of class A devices, updates the location, and offline messages.
The OnClose function triggers a shutdown event to remove a connection from the connection pool.
After the Websocketdeviceinbound constructor establishes a connection for the client, Websocketservlet's createwebsocketinbound function fires, querying the detailed data of the class A/B device in the background database and instantiating it Connecteddevice as a member variable for Websocketdeviceinbound, the Websocketservlet class now joins the new Websocketinbound instance to the custom Websocketdeviceinboundpool connection pool for unified processing of business logic such as A/b device crew relationship and location distribution information calculation.
Websocketdeviceinboundpool class
Websocketinboundpool class: Due to the need to deal with a large number of class A B device real-time messages, the server will have a large number of HTTP long connections, for unified management and efficient use of HTTP long connection resources, the project uses a simple HASHMAP memory connection pooling mechanism, each device Log in the newly created websocketinbound into the connection pool of the Websocketinbound instance, and remove the corresponding Websocketinbound instance from the connection pool when the device is logged out.
In addition, the Websocketinboundpool class also undertakes the role of WebSocket clients in handling the message passing between Class A and class B devices, where the server Websocketinboundpool is located when the client sends a Class A device login, logout, and location update message. The calculation of the distributed information and pushes the computed results to a class B device that is also online.
Listing 8.websocketdeviceinboundpool.java code example
public class Websocketdeviceinboundpool {private static final arraylist<websocketdeviceinbound> connections =new Arraylist<websocketdeviceinbound> ();p ublic static void Addmessageinbound (Websocketdeviceinbound inbound) {// Add Connection Deviceaccount da = Inbound.getconnecteddevice (); System.out.println ("New on-line device:" + da.getdevicenm ()); Connections.add (inbound);} public static arraylist<deviceaccount> getonlinedevices () {arraylist<deviceaccount> onlineDevices = new Arraylist<deviceaccount> (); for (Websocketdeviceinbound webclient:connections) {Onlinedevices.add ( Webclient.getconnecteddevice ());} return onlinedevices;} public static Websocketdeviceinbound getgroupbdevices (String Group) {Websocketdeviceinbound retwebclient =null;for ( Websocketdeviceinbound webclient:connections) {if (Webclient.getconnecteddevice (). Getdevicegroup (). Equals (group) &&webclient.getconnecteddevice (). GetType (). Equals ("B")) {retwebclient = webClient;}} return retwebclient;} public static void RemovemessageiNbound (Websocketdeviceinbound Inbound) {//Remove connection System.out.println ("Device offline:" + inbound.getconnecteddevice ()); Connections.remove (inbound);} public static void Processtextmessage (Websocketdeviceinbound inbound,string message) {BaseEvent receiveevent = ( BaseEvent) Json.parseobject (message.tostring (), Baseevent.class);D Beventhandleimpl dbeventhandle = new Dbeventhandleimpl ();d beventhandle.setreceiveevent (receiveevent);d beventhandle.handleevent (); Receiveevent.geteventtype () ==eventconst.event_matchmatic_result| | Receiveevent.geteventtype () ==eventconst.event_group_devices_result| | Receiveevent.geteventtype () ==eventconst.event_a_repaire) {String Clientdevicegroup = ((arraylist<deviceaccount > Receiveevent.geteventobjs ()). Get (0). Getdevicegroup (); Websocketdeviceinbound bclient = getgroupbdevices (Clientdevicegroup), if (bclient!=null) {sendMessageToSingleClient ( Bclient,dbeventhandle.getreceiveevent ());}}} public static void Sendmessagetoalldevices (BaseEvent event) {try {websocketdeviceinbound WebcLient:connections) {webclient.sendmessage (event);}} catch (Exception e) {e.printstacktrace ();}} public static void Sendmessagetosingleclient (Websocketdeviceinbound webclient,baseevent event) {try { Webclient.sendmessage (event);} catch (Exception e) {e.printstacktrace ();}}}
Code Explanation:
The Addmessageinbound function adds clients to the connection pool to establish a good connection.
The Getonlinedevices function gets all the lines of A/B class device.
The Removemessageinbound function implements A class A device or class B device to exit offline (the server receives a client shutdown WebSocket connection event, triggering the OnClose method in Websocketinbound), removing the connection from the connection pool of the connecting device client Connect to the instance.
Processtextmessage completes the processing of client messages, which uses the mechanism of message processing, including decoding client messages, constructing event events based on messages, Eventhandle multithreading, returning to the client after processing, and the ability to push messages to the group B device. You can also push messages to the client that sends the message.
The Sendmessagetoalldevices function implements sending data to all online A/b class device clients. The Sendmessagetosingleclient function implements sending data to a A/B class device client.
Websocket.js Client Code
Client code Websocket.js, the client uses the WebSocket API defined by the standard HTML5, thus guaranteeing the support of multiple browsers such as Ie9+,chrome,firefox, and the processing and sending of JSON data in conjunction with the JQUERYJS library API.
Listing 9: Sample client Websocket.js Script
var Websocket=window. WebSocket | | Window. Mozwebsocket; var isconnected = false;function Doopen () {isconnected = true;if (devicetype== ' B ') {maparea= ' MAPB '; dologinb (MapArea);} E lse{maparea= ' MapA '; Dologina (Maparea);}} function Doclose () {showdiagmsg ("Infofield", "Disconnected", "infodialog"); isconnected = false;} function Doerror () {showdiagmsg ("Infofield", "Connection Exception!", "Infodialog"); isconnected = false;} function domessage (message) {var event = $.parsejson (message.data);d oreciveevent (event);} function dosend (message) {if (websocket! = null) {Websocket.send (json.stringify (message));} else {showdiagmsg (" Infofield "," You have dropped the line and cannot communicate with the server! "," Infodialog ");}} The initial session websocketfunction Initwebsocket (Wcurl) {if (window. WebSocket) {WebSocket = new WebSocket (encodeURI (Wcurl)); websocket.onopen = Doopen;websocket.onerror = Doerror; Websocket.onclose = Doclose;websocket.onmessage = Domessage;} Else{showdiagmsg ("Infofield", "your device does not support websocket!", "Infodialog");}}; function Doreciveevent (event) {//device not present, client disconnects if (event.eventtype==101) {showdiagmsg ("Infofield", "Device not present or device number password wrong!", "Infodialog"); Websocket.close ();} Return group device and calculate target location information, update map else if (event.eventtype==104| | event.eventtype==103) {cleargmapoverlays (MAPB); $.each (Event.eventobjs,function (idx,item) {var devicenm = item.devicenm;//google api//var devicelocale = new Google.map S.LATLNG (Item.lag,item.lat);//baidu API var Devicelocale = new Bmap.point (Item.lng,item.lat); var Newmarker; if (item.status== ' target ') {Newmarker = Addmarktomap (mapb,devicelocale,devicenm,true);//... The following code is omitted} else{Newmarker = Addmarktomap (MAPB,DEVICELOCALE,DEVICENM);} Markarray.push (Newmarker); }); Showdiagmsg ("Infofield", "There are new repair equipment or equipment offline, the map has been updated!" "," Infodialog ");}}
Code Explanation:
The Doopen callback function handles opening the Websocket,a class device or a class B device connected to the WebSocket server, initializes the map and displays the default location, and then sends the device login message to the server.
The Doreciveevent function handles shutting down the Websocket,a class/class B device (exiting the app on the mobile terminal), the server closes the HTTP long connection, and the client WebSocket object executes the OnClose callback handle.
Initwebsocket initializes the WebSocket, connects the WebSocket server, and sets the processing callback handle if the browser version is too low and does not support HTML5, prompting the client device to not support WebSocket.
The Dosend function handles the client sending a message to the server, noting that the message is a JSON OBJ object that formats the string through the JSON standard API.
The Domessage function handles the messages returned by the WebSocket server, and the message returned in the background is a JSON string, formatted as a JSON Object by the Parsejson API of JQuery for the client to process Doreciveeven The T function when the client receives the service-side return message specific processing, due to a large number of business logic is not mentioned here.
Conclusion
The above briefly introduces the origin of WebSocket, the principle mechanism and the service side/client implementation, and guides and explains how to use WebSocket to solve the problem of real-time response and service-side message push with the actual customer case. This article is intended for readers familiar with the HTML protocol specification and Java EE WEB programming, and is designed to help readers quickly familiarize themselves with the HTML5 WebSocket principles and development applications. The server and client project code in this article is available for download and can be modified for use in the actual production environment of the user's WebSocket-based HTTP long connection.
"Turn" websocket detailed