Java EE HTML5 WebSocket Example

Source: Internet
Author: User
Tags glassfish

1. Introduction HTML5 brings the ability of a full-duplex TCP connection WebSocket a standard server to a Web browser.

In other words, the browser is able to establish a connection with the server, sending and receiving data through the established communication channels without the need for additional overhead to be introduced by the HTTP protocol.

WebSocket offers a popular technology to replace the AJAX technology we've been using for the past few years. This new API provides a way to effectively push messages to the server from the client using simple syntax. The great thing about the WebSocket API is that servers and clients can push information to each other at any point within a given time frame. WebSocket is not limited to communicating in Ajax (or XHR), because Ajax technology requires client-initiated requests, and WebSocket servers and clients can push information to each other, xhr are constrained by domains, and WebSocket allows cross-domain communication.


In this tutorial, we will implement a simple Websockect server side to interact with the client in a Java EE environment.
This tutorial requires the following environments:
Ubuntu 12.04
JDK 1.7.0.21
Glassfish 4.0
Note: WebSocket is only introduced in Java EE 7.

2. WebSocket Server Side
Let's define a Java EE websocket server side:

Websockettest.java

Package com.byteslounge.websockets; Import java.io.IOException; Import Javax.websocket.onclose;import Javax.websocket.onmessage;import Javax.websocket.onopen;import Javax.websocket.session;import Javax.websocket.server.ServerEndpoint; @ServerEndpoint ("/websocket") public class Websockettest {@OnMessage public void OnMessage (String message, Session sess Ion) throws IOException, interruptedexception {//Print the client message for testing purposes SYSTEM.OUT.PR       Intln ("Received:" + message);       Send the first message to the client Session.getbasicremote (). SendText ("This is the first server message");    Send 3 messages to the client every 5 seconds int sentmessages = 0;      while (Sentmessages < 3) {Thread.Sleep (5000);        Session.getbasicremote (). SendText ("This was an intermediate server message.      Count: "+ sentmessages);    sentmessages++; }//Send a final message to the client Session.getbasicremote (). SendText ("ThiS is the last Server message ");  } @OnOpen public void OnOpen () {System.out.println ("Client connected");  } @OnClose public void OnClose () {System.out.println ("Connection closed"); }}


you may have noticed that we introduced some classes from the Javax.websocket package.


@ServerEndpoint annotation is a class-level annotation whose function is to define the current class as a websocket server side. The value of the annotation will be used to listen to the terminal access URL address of the user connection.


The OnOpen and OnClose methods were annotated by @onopen and @onclose respectively. The role of these two annotations is self-explanatory: They define the method that is called when a new user connects and disconnects.


The OnMessage method is annotated by @onmessage. This annotation defines the method that is called when the server receives a message sent by the client. Note: This method may contain a Javax.websocket.Session optional parameter (in our case, the session parameter). If this parameter is present, the container will inject the connection session of the current sending message client.


In this case we just print out the contents of the client message, and first we will send a start message, then 5 seconds to send 1 test messages to the client, send a total of 3 times, and finally send the last end message to the client.


3. Clientnow we're going to write the client for the WebSocket test app:
Page.html

<!  DOCTYPE html>
This is a simple page that contains JavaScript code that creates a WebSocket connection to the WebSocket server side.
OnOpen This method is called when we create a connection to the server.
OnError This method is called when a client-server communication error occurs.
OnMessage This method is called when a message is received from the server. In our case, we just added the message obtained from the server to the DOM.
We connect to the WebSocket server side, use the constructor new WebSocket () and pass it to the endpoint URL:
Ws://localhost:8080/byteslounge/websocket

4. Testingwe can now test our application by visiting the test page:
Http://localhost:8080/byteslounge/page.html
As expected, we will see the Connection established message:

Http://localhost:8080/byteslounge/page.html


Now as soon as we press the button, we send the initialization message to the server through this websocket, and then we receive a test message from the server:
Messages sent by the server and received by the client


5. WebSockets Handshakeclient and server-side TCP connections are established after the HTTP protocol handshake occurs. With HTTP traffic debugging, it's easy to see the handshake. As soon as the client creates a WebSocket instance, the following request and server-side response will appear:
Note: We only entered the HTTP header used by the WebSocket handshake.
Request:
Get/byteslounge/websocket http/1.1
Connection:upgrade
Upgrade:websocket
sec-websocket-key:wvluj/tu9g6ebzeh51idvq==
Response:
http/1.1 101 Web Socket Protocol Handshake
Upgrade:websocket
sec-websocket-accept:2tnh+0h5gtx019lci6mnvs66psy=
Note: The connection requires that the protocol be upgraded to a WebSocket protocol that supports WebSocket HTTP headers via upgrade and upgrade. The server response indicates that the request was accepted and the protocol is converted to the WebSocket protocol (HTTP status code 101):
http/1.1 101 Web Socket Protocol Handshake


6. Download the source codeat the end of this page there is a sample source code download link, the source in GlassFish 4 (requires a compatible Java EE 7 server) to pass the test.
Download the sample source code at the following address:

http://download.csdn.net/detail/we_shell/8115061


English original Http://www.byteslounge.com/tutorials/java-ee-html5-websocket-example


Java EE HTML5 WebSocket Example

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.