WebSocket Brief Introduction

Source: Internet
Author: User

Java back-end websocket Tomcat Implementation I. WebSocket BRIEF INTRODUCTION

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 in versions above Tomcat7.0.47 to run.

Two. websocket example 2.1. New Javaweb Test Project

  

Adding a Jar package dependency in Pom.xml

1 <dependency>2         <groupid>javax</groupid>3         <artifactid>javaee-api</artifactid >4         <version>7.0</version>5         <scope>provided</scope>6 </dependency>

  Client (web home page) code:

 1 <%@ page language= "java" pageencoding= "UTF-8"%> 2 <!  DOCTYPE html> 3 

  Java Web back-end code

 1 package me.gacl.websocket; 2 3 Import java.io.IOException; 4 Import Java.util.concurrent.CopyOnWriteArraySet; 5 6 Import javax.websocket.*; 7 Import Javax.websocket.server.ServerEndpoint; 8 9/**10 * @ServerEndpoint annotation is a class-level annotation, its function is mainly to define the current class as a websocket server side, 11 * Annotation value will be used to listen to the user connection terminal access URL address, The client can connect to the WebSocket server by this URL */13 @ServerEndpoint ("/websocket") public class Websockettest {15//static variable, used to record the current online connection Number. 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 enable the server to communicate with a single client, you can use a map to store it, where key can identify the user with the private static copyonwritearrayset<websockettest> Websocketset =     New Copyonwritearrayset<websockettest> (); 20 21//connection session with a client, which is required to send data to the client. Session SESSION;23 24 /**25 * Connection established method of successful call * @param session optional parameters. Session is connected to a client, it is necessary to send data to the client */28 @OnOpen29 public void OnOpen (session session) {This.sessi on = 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 OnClose ()  {Websocketset.remove (this);           Remove the Subonlinecount () from set; Online number minus 143 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 sends over messages * @par AM Session optional parameter */51 @OnMessage52 public void OnMessage (String message, session session) {Syste M.OUT.PRINTLN ("Message from client:" + message); 54//Mass message for (Websockettest Item:websocketset) {A-Z try {item.sendmessage (message); IOException} catch (e) {E.printstacktrace (); continue;61}62}63}64 65/**66 * Call @param session6 when an error occurs 8 * @param error69 */70    @OnError71 public void OnError (session session, throwable error) {System.out.println ("error occurred"); 73 Error.printstacktrace (); 74}75 76/**77 * This method is not the same as the above methods. Without annotations, it is based on the method you need to add. message79 * @param * @throws IOException80 */81 public void SendMessage (String message) throws Ioexc Eption{82 this.session.getBasicRemote (). SendText (message);//this.session.getasyncremote (). SendText (Mess (age);}85-n-public static synchronized int Getonlinecount () {return onlinecount;88}89 Blic static synchronized void Addonlinecount () {websockettest.onlinecount++;92}93 94 public static SYN chronized void Subonlinecount () {websockettest.onlinecount--;96}97}
1.2. Operation Effect

At the same time open Google browser and Firefox browser for multi-client simulation test, the effect is as follows:

  

The demo is tested under jdk1.7+tomcat7.0.65 environment, sample project code download

This blog content reproduced from http://www.cnblogs.com/xdp-gacl/p/5193279.html, here to thank the author.

WebSocket Brief Introduction

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.