WebSocket is a simple demo program based on javaweb + tomcat, and websocketjavaweb

Source: Internet
Author: User

WebSocket is a simple demo program based on javaweb + tomcat, and websocketjavaweb

As required by the project, after the frontend initiates a request to the background, the background must be divided into multiple steps for relevant operations, and the time required for completing each step cannot be determined.

If ajax is used to repeatedly access the background to obtain real-time data, it is obviously not suitable, whether it is a waste of resources for the client or the server

In this case, WebSocket can solve this problem

Unlike normal http requests or ajax requests, the connection is closed when the corresponding results are returned.

WebSocket seems to be a persistent connection in my personal knowledge. It can maintain connections and send and receive data at any time.

Therefore, I have a preliminary understanding of WebSocket and tried a simple demo according to the relevant tutorials.

 

First, you need to know several basic WebSocket operations.

 

Both the server and client can listen to three basic events:

1. onopen (open connection) 2. onmessage (send data) 3. onclose (close connection)

In this demo, Tomcat 7.0 is used as the server. It is reported that only Versions later than support WebSocket.

 

First, use eclipse to create a web project

Import the WEB-INF and tomcat7-websocket.jar in the tomcat7.0 lib folder in the websocket-api.jar/lib directory under the project root directory

Then create the first class in the src directory (the focus is to inherit ServerApplicationConfig)

Package cn. test. websocket; import java. util. set; import javax. websocket. endpoint; import javax. websocket. server. serverApplicationConfig; import javax. websocket. server. serverEndpointConfig; public class ApplicationConfig implements ServerApplicationConfig {// scan annotation @ Override public Set <Class <?> GetAnnotatedEndpointClasses (Set <Class <?> Scan) {System. out. println ("scan WebSocket" + scan. size (); // return (for filtering, you can filter the face class before returning) return scan ;} // implementation interface @ Override public Set <ServerEndpointConfig> getEndpointConfigs (Set <Class <? Extends Endpoint> arg0) {// TODO Auto-generated method stub return null ;}}

Next, create the second class, which is used to process the data transmitted by WebSocket (the focus is that the class has the annotation of @ ServerEndpoint)

Package cn. test. websocket; import javax. websocket. OnClose;
Import javax. websocket. CloseReason;
Import javax. websocket. endpointConfig; import javax. websocket. onMessage; import javax. websocket. onOpen; import javax. websocket. session; import javax. websocket. server. serverEndpoint; // specifies the URL to access @ ServerEndpoint ("/echo ") public class EchoSocket {/*** this method will be called when the client is connected */@ OnOpen public void open (Session session, EndpointConfig config) {System. out. println (session. getId () + "#############");} /*** this method will be called when the client is disconnected */@ OnClose public void close (Session session, CloseReason reason) {System. out. println (session. getId () + "Connection closed");}/*** receive client information * @ param msg * @ param last */@ OnMessage public void message (Session session, boolean last, String msg) {System. out. println ("client said" + msg); try {session. getBasicRemote (). sendText ("ni hao too"); Thread. sleep (3000); // send another message three seconds later to verify whether the session is updated in real time. getBasicRemote (). sendText ("ni hao too twice");} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();}}

/*** Error listening (an exception occurs when the browser is closed without closing the socket connection )*/

@ OnError
Public void error (Session session, Throwable error ){
String id = session. getId ();
System. out. println ("the error session id is" + id );
}

Public EchoSocket () {System. out. println ("Socket object creation"); // you can know that communication between different sockets does not share member variables through object creation }}

In this case, the annotation-based method is used to enable ApplicationConfig to scan the annotation.

(In fact, there are methods to implement interfaces. Similarly, you can use ApplicationConfig to scan classes that implement interfaces)

 

The classes required by the background have been written. Next, we will write a simple jsp page.

The index. jsp in the project is as follows (in fact, html can also be used)

<% @ Page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 

Now, the demo has been compiled. Deploy the project to tomcat 8080, start tomcat, and access localhost:/WebSocket. The following simple page is displayed:

 

 

Click the open button to initiate a websocket connection. The server console will output

Create a Socket object
0 #############

Enter "hello" in the webpage input box and click "send ".

Server console output

Hello, client

"Ni hao too" is displayed on the webpage. After three seconds, "ni hao too twice" is displayed"

(3 seconds is too short to capture the first effect image, 2333 of what everyone knows)

 

 

Repeat and enter information on the webpage. After clicking "send", the same effect will be displayed again.

Obviously, WebSocket is flexible and easy to use.

 

(Ps: The first article is a casual article. When new recruits arrive, there will inevitably be many missing or wrong places. Please give more advice to our predecessors)

 

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.