Websocket in HTML5

Source: Internet
Author: User
Introduction:Prepare some HTML5 new technologies to enhance the project tools. The design background interaction part selects HTML5 websocket, studies the basic usage, and wants to write some feelings about websocket practices.
I personally think that the emergence of websocket is an innovation in Web application interaction design. Before websocket was proposed, some solutions were proposed to solve the requirements of pushing messages to the foreground in the background. These solutions use existing technologies (such as Ajax, IFRAME, flashplayer, java Applet ...), it is implemented through some flexible processing. The basic idea is to keep the client
Browser requests any data and page changes to the server, or uses a third-party plug-in through persistent connection to instantly receive data from the server.
Websocket allows the backend to send text or binary messages to the front end at any time. websocket is a brand new protocol that does not belong to the HTTP stateless protocol. The protocol name is "ws ", this means that a websocket connection address is written as follows: WS: // localhost: 8080/websocketserver. WS are not HTTP, so traditional Web servers do not necessarily support them. They must be supported by both the server and the browser,
Websocket can run normally. Currently, it is not widely supported and requires special web servers and modern browsers. The following is the browser's support for websocket:

Next, let's take a look at the common architecture of the Application Based on websocket: it supports more concurrent connections, and because of its bidirectional nature in principle, the client connection can penetrate the net to the background server with a firewall and proxy. Because the communication protocol of websocket is not HTML, in the new ws communication protocol design, the size of transmitted messages is greatly reduced, removing the traditional html
Packet has many redundant information. Messages after slimming can also greatly improve the response performance of Web applications.

Demonstration:Currently, more web servers are supported for websocket, in practice, I chose jetty 8.1.4 to include a jetty-websocket JRA package in jetty's lib to implement the websocket interface specification released by W3C, in addition, Jetty-util also contains the communication message conversion class in JSON format. This facilitates developers to quickly develop websocket applications. The main part of the background code is: 1. Inherit and implement dowebsocketconnection method in websocketservlet 2. Implement onopen, onclose, onmessage and other methods in websocket Interface
public class AutoAdminServlet extends WebSocketServlet{//private static final long serialVersionUID = 1874288265454885922L;private final Set<AutoAdminSocket> clients;static Logger LOG = Logger.getLogger(AutoAdminServlet.class);public AutoAdminServlet(){clients = new HashSet<AutoAdminSocket>();}@Overridepublic WebSocket doWebSocketConnect(HttpServletRequest req, String message) {LOG.info("Set up a web socket connection: "+message);return new AutoAdminSocket();}class AutoAdminSocket implements WebSocket.OnTextMessage{WebSocket.Connection connection;@Overridepublic void onMessage(String message) {/*Object json = JSON.parse(message);if(!(json instanceof Map))return;@SuppressWarnings("unchecked")Map<String, String> map = (Map<String, String>)json;//TODO*/sendMessage(this, null, "Thanks, I received: "+message);}@Overridepublic void onClose(int code, String message) {LOG.info("Closed and removed a client socket connection.");clients.remove(this);}@Overridepublic void onOpen(Connection conn) {LOG.info("Received a client socket connection.");this.connection = conn;clients.add(this);sendMessage(this, "open", "sample data");}}void sendMessage(AutoAdminSocket client, String action, String message){try{if(message == null || message.isEmpty())message = "n/a";if(action != null)message = "action: "+action+", data: "+message;client.connection.sendMessage(message);}catch(IOException ex){ex.printStackTrace();}}}

Front-end Page code, mainly do the following: 1. determine whether the browser supports websocket in Javascript, and provide some friendly tips or filing solutions 2. create a websocket JavaScript Object and manage it with caution: avoid misuse and constantly establish a websocket with the server. Generally, a browser terminal can maintain a connection. The logic diversity can be enriched through the command mode. when Browser needs to actively communicate with the server, call the send Method 4 in the websocket API. when the server actively pushes data to the browser, the onmessage method dispatch diverse business

var log = function(s) {      if (document.readyState !== "complete") {          log.buffer.push(s);      } else {          document.getElementById("output").innerHTML += (s + "\n");      }  }log.buffer = [];  var socket = null;function init(){window.WebSocket = window.WebSocket || window.MozWebSocket;if(!window.WebSocket){log("WebSocket not supported by this browser");return;}var webSocket = new WebSocket("ws://127.0.0.1:8080/pulsenet/auto");webSocket.onopen = onopen;webSocket.onclose = onclose;webSocket.onmessage = onmessage;socket = webSocket;}function onopen(){log("Open a web socket.");}function onclose(){log("Close a web socket.");}function onmessage(evt){var data = evt.data;if(!data)return;log(data);data = JSON.parse(data);if(!data)return;}function send(){socket.send("Hello web socket server!");}

EndAfter experiencing websocket, I summarized some ideas: 1. the background code of websocket requires a robust and clear algorithm to determine which messages are pushed to which clients, one or more, or all pushes similar to broadcasts, to manage the socket connection of the client, thread security and uniqueness must be considered. 2. The front-end code of webcoekt needs to design concise protocols or commands based on business, as well as data formats, to transfer the polling responsibility to the server, while the browser only focuses on the logic of active requests. When receiving the active requests from the server push and client to operate on the common part of the page, you must also carefully design the logic and synchronization of page data presentation.
Reference:1. W3C websocket API: http://www.w3.org/TR/2011/WD-websockets-20110419/2. websocket a good introduction: http://websocket.org/aboutwebsocket.html


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.