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 continuously request any data and page changes from the Client Browser to the Server through polling, or to receive Server data in real time by using third-party plug-ins through persistent connections.
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 is not http, so traditional web servers are not necessarily supported. WebSocket can run normally only when the server and browser are supported at the same time, special web servers and modern browsers are required. 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 message transmission is greatly reduced, removing a lot of redundant information from the traditional HTML Packet. 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.
The Jetty lib contains a JRA package of jetty-websocket which implements the WebSocket interface specification released by W3C and also contains the communication message conversion class based on JSON format in jetty-util. This facilitates developers to quickly develop WebSocket applications. The main part of the background code is:
1. Inherit and implement the doWebSocketConnection method in WebSocketServlet
2. Implement onOpen, onClose, onMessage and other methods in the WebSocket Interface
[Java]
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> ();
}
@ Override
Public 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;
@ Override
Public 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 );
}
@ Override
Public void onClose (int code, String message ){
LOG.info ("Closed and removed a client socket connection .");
Clients. remove (this );
}
@ Override
Public 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/";
If (action! = Null)
Message = "action:" + action + ", data:" + message;
Client. connection. sendMessage (message );
} Catch (IOException ex ){
Ex. printStackTrace ();
}
}
}
The front-end Page code is mainly used to 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.
3. When the Browser needs to actively communicate with the Server, call the send method in the WebSocket API
4. When the Server actively pushes data to the Browser, the onMessage method dispatch diverse business
[Javascript]
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. WebSocket;
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! ");
}
Author: Ant_Yan