With the development of the Internet, the traditional HTTP protocol has been difficult to meet the increasingly complex needs of web applications. In recent years, with the birth of HTML5, the WebSocket protocol has been proposed, it realizes full duplex communication between browser and server, expands the communication function between browser and service, and enables the server to send data to the client actively.
We know that the traditional HTTP protocol is stateless, each request must be initiated by the client (such as a browser), the server to return response results after processing, and the service side is very difficult to actively send data to the client, the client is the active side, The traditional Web mode with the passive side of the server is less troublesome for Web applications where information is not changing frequently, but it is inconvenient for Web applications involving real-time information, such as applications with instant messaging, real-time data, and subscription push. Before the WebSocket specification was introduced, developers would often use a compromise solution: Polling (polling) and Comet technology to achieve these real-time features. In fact, the latter is also a kind of polling, but some improvement.
Polling is the most primitive solution for implementing real-time Web applications. Polling technology requires clients to periodically send requests to the server at set intervals, frequently querying for new data changes. Obviously, this approach leads to excessive unnecessary requests, wasteful traffic, and server resources.
Comet technology can also be divided into long polling and streaming technology. Long polling improves the polling technology mentioned above, reducing useless requests. It sets the expiration time for some data and sends the request to the server when the data expires, a mechanism suitable for data changes that are not particularly frequent. Streaming technology usually refers to the client using a hidden window and the server to establish an HTTP long connection, the server will constantly update the connection state to keep the HTTP long connection to survive, so that the server can use this long connection to actively send data to the client; streaming technology in a large concurrency environment, May test performance on the server side.
Both of these technologies are based on the request-response model, which is not really real-time technology; Each request and response wastes a certain amount of traffic on the same header information, and the complexity of the development is greater.
With the launch of the HTML5 WebSocket, the real real-time communication of the web, so that b/s model with the C/s mode of real-time communication capabilities. WebSocket Workflow is this: the browser through JavaScript to the server to establish a WebSocket connection request, after the WebSocket connection is established successfully, the client and the server can transfer data over a TCP connection. Because the WebSocket connection is essentially a TCP connection and does not require duplicate header data per transmission, it has a much smaller data transfer than polling and comet technology. This article does not introduce the WebSocket specification in detail, mainly introduces the implementation of the next websocket in the Java Web.
Java EE 7 shows the Jsr-356:java API for WebSocket specification. Many web containers, such as Tomcat,nginx,jetty, support WebSocket. Tomcat starts with support for WebSocket from 7.0.27, supports JSR-356 from 7.0.47, and the following demo code needs to be deployed on Tomcat7.0.47 to run.
Create a new Dynamic Web project:
Client (web home page) code:
1 <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> 2 <% 3 String path = REQUEST.GETCONTEXTPA Th (); 4 String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; 5%> 6 7 <! DOCTYPE html> 8 Java Web back-end code
1 package com.chen.websocket; 2 Import java.io.IOException; 3 Import Java.util.concurrent.CopyOnWriteArraySet; 4 5 Import Javax.websocket.OnClose; 6 Import Javax.websocket.OnError; 7 Import Javax.websocket.OnMessage; 8 Import Javax.websocket.OnOpen; 9 Import javax.websocket.session;10 Import javax.websocket.server.serverendpoint;11 12//This annotation is used to specify a URI, The client can use this URI to connect to the WebSocket. A servlet-like annotation mapping. No need to configure in Web. Xml. @ServerEndpoint ("/websocket") public class Mywebsocket {15//static variable, used to record the current number of online connections. It should be designed to be thread-safe. The private static int onlinecount = 0;17//concurrent package is a thread-safe set that holds the corresponding Mywebsocket object for each client. To implement a service-side communication with a single client, you can use a map to store it, where key can identify the user with the private static copyonwritearrayset<mywebsocket> Websocketset = new Copyonwritearrayset<mywebsocket> (); 20 21//connection session with a client, which is required to send data to the client. Private session SESSION;23 24/**25 * 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 */28 @OnOpen29 publicvoid OnOpen (Session session) {this.session = session;31 websocketset.add (this); Add set in Addonlinecount (); Online number plus 133 System.out.println ("There are new connections added! The current number of online people is "+ getonlinecount ()); 34}35 36/**37 * Method of connection shutdown call */39 @OnClose40 public void Oncl OSE () {websocketset.remove (this); Remove the Subonlinecount () from set; Online number minus 1 System.out.println ("There's a connection off!") The current number of online people is "+ getonlinecount ()"); 44}45 46/**47 * method called after receiving a client message * @param message client sent over 49 * @param session optional parameter */51 @OnMessage52 public void OnMessage (String message, session session) {53 SYSTEM.OUT.PRINTLN ("Message from client:" + message); 54 55//Mass message for (Mywebsocket Item:websocketset) { Item.sendmessage (message); catch (IOException e) {60 E.printstacktrace (); continue;62}63}64}65 66/**67 * When an error occurs, it is called @param session69 * @param error */71 @OnError72 public void OnError (session session, throwable error) {System.out.println ("error occurred" ); Error.printstacktrace (); 75}76 77/**78 * This method is not the same as the above methods. Without annotations, it is based on the method you need to add. MESSAGE80 * @param * @throws IOException81 */82 public void SendMessage (String message) throws Ioexc eption{83 this.session.getBasicRemote (). SendText (Message),//this.session.getasyncremote (). SendText (Mess age);}86, synchronized, public static, int getonlinecount () {onlinecount;89}90 91 public static synchronized void Addonlinecount () {mywebsocket.onlinecount++;93}94-Stati c synchronized void Subonlinecount () {mywebsocket.onlinecount--;97}98}
The demo has been tested in the following environments:
1.jdk7+tomcat7.0.47
2.jdk7+tomcat7.0.52
3.jdk7+tomcat8.0.3
4.jdk7+glassfish4
Note: In eclipse or myeclipse, you need to add Tomcat's library. A direct copy of the jar package in the Tomcat Lib directory can sometimes be an error.
Article posted: http://blog.chenzuhuang.com/archive/28.html
The tomcat implementation of Java back-end WebSocket