WebSocket Java Programming Getting Started-1 (annotated)

Source: Internet
Author: User

1. Preface

has not been how to do the front-end things, but the recent project, the front-end personnel scarce, the company does not arrange for new personnel to enter, so I this background developer can only pull over to sit front end, the front section of things feel a lot, css,js from needless to say, the HTML ecosystem has a lot of technology to learn, okay, Then one of the learning to organize, first of all, the recent project of the front end of the use of what technology it.

1, Restful:dropwizard This is very simple, two days basically can win

2, JS Framework:angularjs This JS library is really cool, the recent learning process more and more like this thing, and plan to organize some AngularJS study notes and process

3, the front-end and back-end communication is not the kind of request and response way, but the use of HTML5 websocket.

4, other technology I will not list the

In the process of learning WEBSOCKET I read the WEBSOCKET of Tomcat examples of course the most important thing is to read a relatively good systematic WEBSOCKET book, recommended to Everyone "JAVA WEBSOCKET Programming" Then I try to learn from myself, as much as possible in a more in-depth introduction, convenient to communicate with you.


2, the environment configuration on the internet about WebSocket is a plethora of articles, I do not have to go to excerpt, first directly to a more intuitive example, this article is based on the annotated way to demonstrate an Echo server instance
2.1. Operating Environment Requirements:The Tomcat version must be7.0. More than 47 versions are availableJDK must be above version 1.7 to be able to2.2, development environment: (do not make mandatory requirements, according to personal hobbies, I just enumerate my development environment) maven:3.0.4 Ide:intellij idea
3, the first annotation-based websocket Demo
Well, everything is ready, let's take a look at the code below, and then I'll one by one explain some of the details 3.1, maven Pom
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:s chemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" > <parent> &L T;artifactid>websocket</artifactid> <groupId>websocket</groupId> <version>1.0-sna pshot</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactid>websocket- anotation</artifactid> <packaging>war</packaging> <name>websocket-anotation Maven webapp&            lt;/name> <url>http://maven.apache.org</url> <dependencies> <dependency>            <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId>        <version>1.0</version> <scope>provided</scope> </dependency>          <dependency>  <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8 .1</version> <scope>test</scope> </dependency> </dependencies> <b Uild> <finalName>websocket-anotation</finalName> </build></project>
Where we introduced the standard API interface for Javax WebSocket and set its scope to provided (the Tomcat container already has this package, and we don't need to publish it again. The purpose of designation as provided is to use it in the process of writing code.
3.2. Service Segment Code:
Package Com.wangwenjun.websocket.annotation;import Javax.websocket.onclose;import Javax.websocket.OnMessage; Import Javax.websocket.onopen;import Javax.websocket.session;import javax.websocket.server.serverendpoint;@ Serverendpoint (value = "/hello") public class Helloworldserver {    @OnMessage public    string SayHello (string Incomingmessage) {        return "I got this (" + Incomingmessage + ") so I am sending it back to you!";    }    @OnOpen public    Void Open (Session session) {        System.out.println ("On open---" + session.getbasicremote ());    }    @OnClose public    Void Close () {        System.out.println ("close.");    }
In fact, as long as there is a method in this example is @onmessage annotations, the other open and close can be ignored temporarily, the websocket way can not only pass the text information with the service segment can also be interactive binary form (InputStream), Not only can you return a string, you can return a binary stream (OutputStream), but you can also get a reference to the entire reply, such as a session, which means that the following methods are reasonable
@OnMessage public    void test1 (String test) {        //do nothing.    }    @OnMessage public    void Test2 (InputStream inputstream) {        //do nothing.    }    @OnMessage public    outputstream test3 (InputStream inputstream) {        //do nothing.        return null;    }    @OnMessage public    void Test4 (String text,session Session) {        //do nothing.    }
And so on and so on, all right, okay, we're going to say that. SayHello, the method accepts a text string and returns a text string, annotated as OnMessage, that accepts information from the client and processes it.
3.3. Client code
<! DOCTYPE html>
Client code about DOM operations I use the most Yuan Sheng processing, and do not use jquery and so on DOM support particularly good third-party library, presumably everyone can see clearly, I do not do more explanation, the key to say WebSocket object, WebSocket objects are not supported in the JS host (browser), IE is starting from the tenth version of support, if you are doing an Internet application, there is no way to force customers to try the unified support WebSocket Object Browser, You'd better be able to determine whether the JS environment supports WebSocket objects, the method of judging is very simple, such as the following several ways can
Method 1        if (window. WebSocket) {        }        //method 2        if ("WebSocket" in window)        {        }                //method 3        if (window["WebSocket "]){                    }
OK, let's take a look at some of the key parts of the JS code above.
var url = "Ws://localhost:8080/websocket-anotation/hello";
Define the address of the WebSocket Serverendpoint, remember that the protocol is WS Oh, do not like me the first time to learn the habitual use of HTTP, the last of the uri/ Hello is the value that we annotate with @serverenmdpoint in our helloworldserver, it should not be difficult to understand.
WS = new WebSocket (URL);
Create a WebSocket object, if you can create a successful use of our websocket, but more rigorous practice should be as I said earlier, should be judged whether the JS host environment supports WebSocket, otherwise the following code will appear wrong.
WebSocket Most beautiful place there are many callback functions inside, when the occurrence of related things will be automatically called, as the following code is registered related callback function
Ws.onopen = function (event) {                writemessagetoscreen ("Connected.");                var Message=document.getelementbyid ("message"). Value;                Dosend (message);            }            Ws.onmessage = function (event) {                writemessagetoscreen ("Received message:" + event.data);                Ws.close ();            }            Ws.onerror = function (event) {                Writemessagetoscreen ("occur error:<span style= ' color:red ' >" + event.data + "& Lt;/span> ");                Ws.close ();            }

The first one is called after a successful connection, and the second is a callback from the Serverendpoint message, and the third is the callback that occurs when the error is made.
The last key method is to send the message to the server, but it has to be admitted that it is really simple, just one line
Ws.send (message);

4. ReleaseSo simple, a few lines of code can achieve a most basic client-server communication with the small program, write here we should publish, see how the new multiple effects, runMVN the Clean Packages command, package the Web project into a war package, then copy it to your Tomcat WebApps directory, or you can install the Tomcat auto-deploy plugin and run the command to automatically publish the war package under WebApps. Interested can try on their own, I do not do a demonstration here, and then visit the page: http://localhost:8080/websocket-anotation/himself play a bar.
5. Brief summary
HTTP is a non-persistent connection protocol, that is, each time and the server interaction is a new connection, we can understand as a TCP-based short connection protocol, but the advent of websocket, to the web developer a long connection to the choice, we can and the service side always stay in touch, and receive information from the service side, in the Internet, based on the application of WEBSOCKET more and more, learning is very necessary, in the next will continue to update, say again "JAVA WEBSOCKET Programming" This book is really good, and only more than 200 pages, After reading to practice, I believe you will be proficient in the use of websocket.

WebSocket Java Programming Getting Started-1 (annotated)

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.