Websocket simple demo Based on jsp + tomcat7.047 + html5

Source: Internet
Author: User

 

The goal of the WebSocketWebSocket specification is to implement bidirectional communication with the server in the browser. Two-way communication can expand the application types on the browser, such as real-time data push (stock quotes), games, and chat. WebSocket protocol is a new HTML5 protocol ). It implements full-duplex communication between the browser and the server ). Currently, many websites use polling to implement real-time communication ). Round Robin is performed at a specific time interval (such as every 1 second). The browser sends an HTTP request to the server and then the server returns the latest data to the client browser. This traditional HTTP request d mode brings obvious disadvantages-the browser needs to constantly send requests to the server. However, the HTTP request header is very long, the data contained in it may be a small value, which will occupy a lot of bandwidth. The most new technology used for polling is Comet-AJAX. However, although this technology can reach full-duplex communication, it still needs to send a request (reuqest ). In the WebSocket API, the browser and the server only need to perform a handshake, and then a fast channel is formed between the browser and the server. Data can be directly transmitted to each other. In this WebSocket protocol, it brings us two benefits for implementing real-time services: 1. the Header that communicates with each other is very small-about 2 Bytes 2. server Push Server can actively send data to client 3 handshake protocol in the Process of websocket connection, you need to send a websocket connection request through the browser, and then the Server sends a response, this process is usually called handshaking ). PS1: the handshake protocol is marked with a version number in later versions. The following example is one of the earlier versions and is not applicable to chrome and Firefox. PS2: Later versions are mostly extended functions. For example, the handshake protocol of version 7th also applies to the handshake protocol of version 8th. Example: Browser requestGET/demo HTTP/1.1 Host: Your URL. com Connection: Upgrade Sec-WebSocket-Key2: 12998 5 Y3 1. p00 Upgrade: WebSocket Sec-WebSocket-Key1: 4 @ 1 46546xW % 0l 1 5 Origin: http: // Your URL. com ^ n: ds [4U Server ResponseHTTP/1.1 101 WebSocket Protocol Handshake Upgrade: WebSocket Connection: Upgrade Sec-WebSocket-Origin: http: // Your URL. com Sec-WebSocket-Location: ws: // Your URL. com/demo Sec-WebSocket-Protocol: sample 8jKS 'y: G * Co, Wxa-4 browser realizes websocket Browser:
Chrome Supported in version 4 +
Firefox Supported in version 4 +
Internet Explorer Supported in version 10 +
Opera Supported in version 10 +
Safari Supported in version 5 +
5. On the server side, there are also some projects that implement the websocket Protocol: jetty 7.0.1 contains a preliminary implementation resin includes websocket to implement pywebsocket, apache http server Extension apache tomcat 7.0.27 Nginx 1.3.13 websocket api extensive implementation on the browser end seems to be only a matter of time. It is worth noting that there is no standard api on the server side, each implementation has its own set of APIS, and jcp does not have similar proposals. Therefore, using websocket to develop the server has certain risks. it may be locked on a platform or be forced to upgrade in the future. ke, the above is from Baidu encyclopedia. Please search for details by yourself
Now, prepare the development environment: java sdk7, Myeclipse10, and atat7.47. After downloading the SDK, install it on your own.
Open MyEclipse to create a JSP project, and then import catalina. jar, websocket-api.jar what, you feel uncomfortable, then you export a few more, anyway, don't money, no one raped you!


OK. Next, create a WebsocketConfig class. For the abstract class ServerApplicationConfig, check javaEE7 api. This is very important.
Package com. websocket; import java. util. hashSet; import java. util. set; import javax. websocket. endpoint; import javax. websocket. server. serverApplicationConfig; import javax. websocket. server. serverEndpointConfig; public class WebsocketConfig implements ServerApplicationConfig {@ Overridepublic Set
 
  
> GetAnnotatedEndpointClasses (Set
  
   
> Scanned) {// TODO Auto-generated method stubSystem. out. println (******* getAnnotatedEndpointClasses *******); // Deploy all WebSocket endpoints defined by annotations in the examples // web application. filter out all others to avoid issues when running // tests on Gump // This is mainly a scan class package, if the prefix is com. websocket. just grab her and then do what, you know Set
   
    
> Res = new HashSet <> (); for (Class
    Cs: scanned) {if (cs. getPackage (). getName (). startsWith (com. websocket .)) {res. add (cs) ;}} return res ;}@ Overridepublic Set
    
     
GetEndpointConfigs (Set
     
      
> Scanned) {// TODO Auto-generated method stubSystem. out. println (****** getEndpointConfigs ******); Set
      
        Res = new HashSet <> (); // if (scanned. contains (EchoEndpoint. class) {res. add (ServerEndpointConfig. builder. create (EchoEndpoint. class,/websocket/echoProgrammatic ). build () ;}*/return res ;}}
      
     
    
   
  
 

Now let's create a simple chat ServerEndpoint. It is said that there are two ways: 1. Use @ ServerEndpoint 2. Use the inheritance method. First, create a new class chat1.
Package com. websocket. chat; import java. io. IOException; import java. util. set; import java. util. concurrent. copyOnWriteArraySet; import java. util. concurrent. atomic. atomicInteger; import javax. websocket. onClose; import javax. websocket. onMessage; import javax. websocket. onOpen; import javax. websocket. session; import javax. websocket. server. serverEndpoint; import util. HTMLFilter; @ ServerEndpoint (value =/chat01) // after this is used, your service address is ws: // localhost: port/projectName/chat01public class chat_1 {private static final AtomicInteger connectionIds = new AtomicInteger (0); private static final Set
 
  
Connections = new CopyOnWriteArraySet
  
   
(); Private final String nickname; private Session session; public chat_1 () {nickname = tourist ID: + connectionIds. getAndIncrement () ;}@ OnOpen public void start (Session session) {this. session = session; connections. add (this); String message = String. format (Hey girls, pick up: % s, nickname, has joined .); broadcast (message) ;}@ OnClose public void end () {connections. remove (this); String message = String. f Ormat (the visitor is walking slowly. Hey hey, you haven't paid yet: % s, nickname, has disconnected .); broadcast (message) ;}@ OnMessage public void receive (String message) {// Never trust the client String filteredMessage = String. format (you have a new message: % s, nickname, HTMLFilter. filter (message. toString (); broadcast (filteredMessage);} private static void broadcast (String msg) {for (chat_1 client: connections) {try {client. session. getBasicRem Ote (). sendText (msg);} catch (IOException e) {connections. remove (client); try {client. session. close ();} catch (IOException e1) {// Ignore} String message = String. format (* % s, client. nickname, has been disconnected .); broadcast (message);} // try} // for} // void broadcast (String msg)}/** you may have noticed that we have. some classes are introduced in the websocket package. @ ServerEndpoint annotation is a Class-level annotation. Its function is to define the current class as a websocket server. The annotation value is used to listen to the terminal access URL address connected to the user. The onOpen and onClose methods are annotated by @ OnOpen and @ OnClose respectively. The functions of these two annotations are self-evident: they define the methods called when a new user connects and disconnects. The onMessage method is annotated by @ OnMessage. This annotation defines the method called when the server receives a message sent from the client. Note: This method may contain an optional javax. websocket. Session parameter (in our example, the session parameter ). If this parameter is set, the container injects the connection Session of the client sending the message. */
  
 


Index. jsp
<%@ page language=java import=java.util.* pageEncoding=ISO-8859-1%><%String path = request.getContextPath();String basePath = request.getScheme()+://+request.getServerName()+:+request.getServerPort()+path+/;%>
>
  • Chat01
 
 
  • Chat02
 
 

OK. Next, we will use the second method, which is my favorite method.

 

 

/* *  Licensed to the Apache Software Foundation (ASF) under one or more *  contributor license agreements.  See the NOTICE file distributed with *  this work for additional information regarding copyright ownership. *  The ASF licenses this file to You under the Apache License, Version 2.0 *  (the License); you may not use this file except in compliance with *  the License.  You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * *  Unless required by applicable law or agreed to in writing, software *  distributed under the License is distributed on an AS IS BASIS, *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *  See the License for the specific language governing permissions and *  limitations under the License. */package websocket.echo;import java.io.IOException;import javax.websocket.Endpoint;import javax.websocket.EndpointConfig;import javax.websocket.MessageHandler;import javax.websocket.RemoteEndpoint;import javax.websocket.Session;public class EchoEndpoint extends Endpoint {    @Override    public void onOpen(Session session, EndpointConfig endpointConfig) {        RemoteEndpoint.Basic remoteEndpointBasic = session.getBasicRemote();        session.addMessageHandler(new EchoMessageHandler(remoteEndpointBasic));    }    private static class EchoMessageHandler            implements MessageHandler.Whole
 
   {        private final RemoteEndpoint.Basic remoteEndpointBasic;        private EchoMessageHandler(RemoteEndpoint.Basic remoteEndpointBasic) {            this.remoteEndpointBasic = remoteEndpointBasic;        }        @Override        public void onMessage(String message) {            try {                if (remoteEndpointBasic != null) {                    remoteEndpointBasic.sendText(message);                }            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }}
 

I will not demonstrate it. Other examples in the Tomcat directory can be found.

 

 

Related Article

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.