Java EE HTML5 WebSocket Example

Source: Internet
Author: User

http://www.oschina.net/translate/java-ee-html5-websocket-example?cmp

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.

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:

    1. Ubuntu 12.04
    2. JDK 1.7.0.21
    3. Glassfish 4.0
Note: WebSocket was introduced in Java EE 7. 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 session) throws IOException, interruptedexception {//Print the Client Me      Ssage for testing purposes System.out.println ("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 are 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 the @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.

Client

Now 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

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.