Java back-end Tomcat Implementation WebSocket Instance tutorial _java

Source: Internet
Author: User
Tags sessions java web

I. WebSocket Brief INTRODUCTION

WebSocket protocol is HTML5 a new protocol. It implements the browser and server Full-duplex communication (Full-duplex). A handshake at the beginning requires an HTTP request to complete the handshake.

With the development of Internet, the traditional HTTP protocol has been difficult to meet the increasingly complex requirements of web applications. In recent years, with the birth of HTML5, the WebSocket protocol has been proposed, which realizes Full-duplex communication between the browser and the server, expands the communication function of the browser and the service side, and enables the service side to send the data to the client actively.

WebSocket background

In the browser can only achieve one-way communication through HTTP, comet can simulate two-way communication to some extent, but the efficiency is low, and need the server to have better support; The sockets and Xmlsocket in Flash enable true two-way communication, and you can use these two features in JavaScript with Flex Ajax Bridge. It can be foreseen that if WebSocket is implemented in the browser, it will replace the above two technologies and be widely used. In the face of this situation, HTML5 defines the WebSocket protocol, which can better save the server resources and bandwidth and achieve real-time communication.

The WebSocket protocol is also implemented in the JavaEE7.

We know that the traditional HTTP protocol is stateless, each request (requests) by the client (such as browser) initiative, the server to deal with the return of response results, and the server can not actively send data to the client; This client is the active side, The traditional Web mode with the passive side is less trouble for Web applications with less frequent information, but it is inconvenient for Web applications involving real-time information, such as instant communication, real-time data, subscription push and other applications. Before the WebSocket specification is presented, developers often use compromise solutions: Polling (polling) and comet technologies to implement these more real-time features. In fact, the latter is essentially a poll, but it has improved.

Polling is the most original 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 can lead to too much unnecessary requests, waste of traffic and server resources.

Comet technology can be divided into long polling and streaming technology. Long polling improves the polling technology described above and reduces unwanted requests. It sets the expiration time for some data and sends the request to the server when the data expires, a mechanism that is not particularly frequent for data changes. Streaming technology usually means that the client uses a hidden window to establish an HTTP long connection with the server. The server will continually update the connection state to keep the HTTP long connection alive; In this way, the server can actively send the data to the client through this long connection; streaming technology in a large concurrency environment, May test the performance of the service side .

Both of these technologies are based on the request-answer model, which is not really a real time technology; each time they request and answer, they waste a certain amount of traffic in the same header information, and the development of complexity is also large.

With the websocket of HTML5, real time communication of the web is realized, which makes the B/s mode have the real-time communication ability of C/s mode. The WebSocket workflow is this: The browser sends a request to the server to establish a websocket connection through JavaScript, and after the WebSocket connection is established, the client and the server can transmit data over the TCP connection. Because the WebSocket connection is essentially a TCP connection and does not require duplicate header data for each transmission, it has a much smaller amount of 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.

The Jsr-356:java API for WebSocket specification is out of Java EE 7. Many web containers, such as Tomcat,nginx,jetty, support WebSocket. Tomcat started supporting WebSocket from 7.0.27, and JSR-356 is supported from 7.0.47, and the following demo code needs to be deployed in more than Tomcat7.0.47 version to run.

Two. WebSocket sample

2.1. New Javaweb Test Project

Add Jar pack Dependencies in Pom.xml

<dependency>
<groupId>javax</groupId>
<artifactid>javaee-api</artifactid >
<version>.</version>
<scope>provided</scope>

Client (web home page) code:

<%@ page language= "java" pageencoding= "utf-"%> <! DOCTYPE html>  

Java Web Back-end code

Package me.gacl.websocket;
Import java.io.IOException;
Import Java.util.concurrent.CopyOnWriteArraySet;
Import javax.websocket.*;
Import Javax.websocket.server.ServerEndpoint; /** * @ServerEndpoint Annotation is a class-level annotation that functions primarily to define the current class as a WebSocket server, and the value of the annotation will be used to monitor the terminal access URL of the user connection. The client can use this URL to connect to the WebSocket server/@ServerEndpoint ("/websocket") public class Websockettest {//static variable, which is used to record the current number of online connections.
It should be designed to be thread-safe.
private static int onlinecount =; The thread-safe set of the concurrent package, which 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 the key that can be identified by the user as private static copyonwritearrayset<websockettest> Websocketset = new
Copyonwritearrayset<websockettest> ();
A connection session with a client, which needs to be sent to the client to send the data private sessions; /** * Connection establishes a successful invocation method * @param session optional parameter.
Session for a connection with a client, you need to send data to the client/@OnOpen public void OnOpen {this.session = sessions; Websocketset.add (this); Add Addonlinecount () to the set; Online number plus SYSTEM.OUT.PRINTLN ("new join!")
Current online number is "+ Getonlinecount ()"); /** * Connection closed the call method */@OnClose public void onClose () {websocketset.remove (this);//Remove Subonlinecount () from set;////Online count minus System.out.println ("There is a connection off!")
Current online number is "+ Getonlinecount ()"); /** * The method called after receiving client messages * @param message client sent over messages * @param session Optional Parameters/@OnMessage public void OnMessage (String messag
E, Session session {SYSTEM.OUT.PRINTLN ("messages from the client:" + message); Mass messages for (Websockettest Item:websocketset) {try {item.sendmessage (message);} catch (IOException e) {E.printstacktrace
();
Continue /** * @param session * @param error/@OnError public void OnError (sessions session, throwable error) {Sys
TEM.OUT.PRINTLN ("error occurred");
Error.printstacktrace (); /** * This method is not the same as the above methods.
Without annotations, it is based on the method you need to add. * @param message * @throws IOException */public void SendMessage (String message) throws ioexception{This.session.getBasi
Cremote (). SendText (message);
This.session.getAsyncRemote (). SendText (message);  public static synchronized int Getonlinecount () {return onlinecount.} public static synchronized void Addonlinecount () {Websockettest.onlinecount++; public static synchronized void Subonlinecount () {websockettest.onlinecount--;}}

1.2. Operation Effect

Simultaneously opens the Google browser and the Firefox browser to carry on the multi client simulation test, the operation effect is as follows:

The above content is a small series to introduce Java back-end Tomcat Implementation WebSocket Example tutorial, I hope to help!

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.