`
wbj0110
  • 浏览: 1604282 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

Java EE HTML5 WebSocket example

阅读更多
In this tutorial we will implement an HTML5 websocket resorting to the Java EE websocket implementation (ServerEndpoint).

1. Introduction

The HTML5 specification brought the capability for web browsers to establish full-duplex TCP connections with websocket compliant servers.

In other words, browsers are now able to establish a connection with a server and keep sending or receiving data through that same established communication channel without the need of the overhead introduced by the HTTP protocol itself.

In this tutorial we will implement a simple websocket server endpoint in a Java EE environment and also the respective client-side infrastructure for sending and receiving data.

This tutorial considers the following environment:

 

  1. Ubuntu 12.04
  2. JDK 1.7.0.21
  3. Glassfish 4.0

 

Note: WebSockets support was introduced in Java EE 7

2. WebSocket server endpoint

Let's define a Java EE websocket server endpoint:

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")publicclassWebSocketTest{@OnMessagepublicvoid onMessage(String message,Session session)throwsIOException,InterruptedException{// Print the client message for testing purposesSystem.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 secondsint sentMessages =0;while(sentMessages <3){Thread.sleep(5000);
      session.getBasicRemote().
        sendText("This is an intermediate server message. Count: "+ sentMessages);
      sentMessages++;}// Send a final message to the client
    session.getBasicRemote().sendText("This is the last server message");}@OnOpenpublicvoid onOpen(){System.out.println("Client connected");}@OnClosepublicvoid onClose(){System.out.println("Connection closed");}}

As you may have already noticed we are importing several classes from javax.websocketpackage.

@ServerEndpoint annotation is used at type level and defines the current class as a websocket server endpoint. The value used in this annotation represents the URL where the endpoint will be listening for client connections.

onOpen and onClose methods are annotated with @OnOpen and @OnClose respectively. These annotations are almost self-explanatory: They define which methods will be called upon a new client connection and disconnection.

Method onMessage is annotated with @OnMessage. This annotation defines which method will be called when a new message is received from the client. Note that this method may be defined with an optional parameter of type javax.websocket.Session (in our case thesession parameter). If this parameter is defined the container will inject the session that is associated with the current client that sent the message being handled.

In our case we are just writing the client message content to the standard output. Then we proceed to send a message to the client followed by 3 test messages with a 5 second interval. Finally we send a final message to the client.

3. Client side

Now we need to write the client-side of our websocket test application:

page.html
<!DOCTYPE html><html><head><title>Testing websockets</title></head><body><div><inputtype="submit"value="Start"onclick="start()"/></div><divid="messages"></div><scripttype="text/javascript">var webSocket =newWebSocket('ws://localhost:8080/byteslounge/websocket');

    webSocket.onerror =function(event){
      onError(event)};

    webSocket.onopen =function(event){
      onOpen(event)};

    webSocket.onmessage =function(event){
      onMessage(event)};function onMessage(event){
      document.getElementById('messages').innerHTML 
        +='<br />'+ event.data;}function onOpen(event){
      document.getElementById('messages').innerHTML 
        ='Connection established';}function onError(event){
      alert(event.data);}function start(){
      webSocket.send('hello');returnfalse;}</script></body></html>

This is a simple test page that contains the JavaScript that will create a websocket connection to out websocket server endpoint.

onOpen method will be called when we establish a connection with the server endpoint.

onError method is called when an error occurs during client-server communication.

onMessage method will be called when a message is received from the server. In our case we are just appending the messages received from the server to the DOM.

We connect to the websocket server endpoint by using the construct new WebSocket() and passing the endpoint URL:

ws://localhost:8080/byteslounge/websocket

4. Testing

We may now test our application by accessing the testing page:

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

We will see the Connection established message as expected:

http://localhost:8080/byteslounge/page.html
Websocket - Connection established

Now as soon as we press the button we will send the initial message to the server through the websocket and receive the subsequent test messages sent by the server:

Messages sent by the server and received by the client
Websocket - Messages exchanged

5. WebSockets Handshake

The TCP connection between the client and the server is established after the occurrence of a handshake over the HTTP protocol. It's easy to observe the handshake by using some HTTP traffic debugger. As soon as we create the WebSocket instance in the client the following request and respective server response will occur:

Note: we will only include HTTP headers that are relevant to the websockets 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 that the client is requesting the protocol to be upgraded to the WebSocket protocol by using Connection: Upgrade and Upgrade: websocket HTTP headers. The server response states that the client request was accepted and it will change protocol to WebSocket (using HTTP status code 101):

HTTP/1.1 101 Web Socket Protocol Handshake

6. Downloadable sample

The example source code is available for download at the end of this page. The test was executed in Glassfish 4 (you will need a Java EE 7 compliant application server).

Download source code from this tutorial

分享到:
评论

相关推荐

    java-ee7-html5-websocket-example

    在"java-ee7-html5-websocket-example"项目中,我们将看到如何结合HTML5和Java EE 7的WebSocket API创建一个即时通信的应用。HTML5是现代网页开发的标准,其中的WebSocket API为浏览器提供了原生支持,使得开发者...

    Java EE 6 tutorial 配套example代码

    5. **JPA**:Java EE 6中的JPA 2.0加强了ORM能力,如 Criteria API 和 Named Query。示例可能展示了如何定义实体类,使用注解配置数据映射,以及执行CRUD操作。 6. **CDI(Contexts and Dependency Injection)**:...

    java-ee-html5-websocket-example:java-ee-html5-websocket-example

    标题中的"java-ee-html5-websocket-example"表明这是一个关于使用Java EE平台,结合HTML5的WebSocket技术实现的示例项目。这个项目可能是为了展示如何在服务器端与客户端之间建立实时、双向通信的通道。 Java EE...

    基于SMTP的JAVA邮件发送基于websocket和java的多人聊天室编程资料程序编程资料

    本案例采用的是HTML5 + WebSocket + Java EE 7 + Tomcat 8的架构。其中Java EE 7规范中引入了WebSocket API,而Tomcat 8则开始支持这个API。 #### WebSocket API Java EE 7中的WebSocket API提供了一系列接口和注解...

    jetty-websocket-example:使用嵌入式Jetty设置WebSocket服务的示例代码

    使用Java SE的Websocket的示例与其使用Java EE及其附带的所有功能,不如使用Java EE,而不是WebSocket的一种较小的实现方式,可能是针对独立程序或嵌入式应用程序的。 该示例将显示使码头服务器运行,为websocket...

    javaee7-jms-websocket-example:集成 JMS 2.0、WebSockets 1.0、CDI 事件和 EJB 3 的 Java EE 7 应用程序示例

    JMS 和 WebSockets 集成的 Java EE 7 示例 此应用程序演示了一个使用 WebSockets 和 JMS 的全双工场景,具有功能齐全的服务器端异步推送,使用 CDI 事件和 EJB。 此处记录了详细信息和分步操作: : 怎么跑 下载并...

    Futures-Java-demo-master_Websocketjava_

    标题"Futures-Java-demo-master_Websocketjava_"和描述"a sample example of java websocket"表明这是一个关于使用Java实现WebSocket协议的示例项目。WebSocket是一种在客户端和服务器之间建立长连接的协议,它允许...

    java程序设计

    "javax"是Java扩展的包名,它通常包含了对标准Java API的扩展或补充,例如 javax.swing 用于图形用户界面(GUI)开发,javax.servlet 和 javax.websocket 用于服务器端编程等。 "com" 是Java中常见的顶级包名,用于...

    2011年1月20日 TOMCAT配置 及EXAMPLE文件夹简单浏览

    标题 "2011年1月20日 TOMCAT配置 及EXAMPLE文件夹简单浏览" 涉及到的是关于Apache Tomcat服务器的配置以及如何理解并使用其自带的EXAMPLES目录。Apache Tomcat是一款开源的Java Servlet容器,主要用于部署和运行Java...

    JavaServlet程序设计初步

    JavaServlet程序设计初步是IT领域中关于Web开发的一项基础技术,它是Java EE(企业版)平台的一部分,用于构建动态Web应用程序。本节将深入探讨JavaServlet的核心概念、工作原理以及如何进行基本的程序设计。 一、...

    Jsp/Servlet3.0 ppt和代码

    3. **WebSocket支持**:Servlet 3.0提供了WebSocket API,使得Java应用可以直接与浏览器进行双向通信,实现低延迟的实时通信功能。 4. **微容器(Microcontainer)**:Servlet 3.0引入了微容器概念,允许开发者在...

    基于Springboot的教学辅助系统(有报告) Javaee项目,springboot项目

    【标题】"基于Springboot的教学辅助系统(有报告) Javaee项目,springboot项目"是一个以Spring Boot为核心技术,用于构建教学辅助管理系统的Java EE项目。这个系统旨在提高教育机构或教师的教学效率,通过数字化...

    tomcat8.0--linux系统

    例如,它支持WebSocket API,这是HTML5的一个重要特性,允许双向实时通信。 安装Tomcat 8.0在Linux上的步骤如下: 1. **更新系统**:首先,确保你的Linux系统是最新的。打开终端并运行以下命令: ``` sudo apt-...

    servlet帮助文档

    Servlet是Java EE(现在称为Jakarta EE)规范的一部分,它允许程序员通过扩展Web服务器的功能来处理HTTP请求。本帮助文档将深入探讨Servlet的工作原理、生命周期、API以及如何在实际项目中有效使用它们。 一、...

    spring学习资料

    它是一个基于Inversion of Control (IoC) 和 Aspect-Oriented Programming (AOP) 架构的框架,旨在简化Java EE系统的开发工作。Spring 的核心理念是“最少侵入性”,这意味着你可以选择何时何地使用它,而不会对现有...

    servlet-2.5-mrel-spec.rar

    Servlet 2.5是Java Servlet技术的一个重要版本,它在2006年发布,是Java EE 5规范的一部分。这个版本对之前的Servlet规范进行了增强和优化,为Web开发提供了更多的功能和灵活性。以下是Servlet 2.5的一些关键知识点...

    中文版Servlet帮助文档

    首先,Servlet是Java EE(现在称为Jakarta EE)的一部分,它是一个服务器端的Java接口,允许程序员编写能够处理HTTP请求的应用程序。Servlet通过扩展Java的HttpServlet类或实现Servlet、ServletConfig、...

    Servlet3.0特性详解

    Servlet3.0是Java EE平台中的一个重要组成部分,它在Servlet2.5的基础上引入了许多新特性,极大地提高了开发效率和灵活性。以下是对Servlet3.0主要特性的详细解释: 1. **注解配置**: 在Servlet3.0中,我们可以...

    Eclipse下的J2EE配置教程

    在市场搜索框中输入"J2EE",会找到"Java EE Developer Tools"插件。点击"Install",按照向导指示完成安装。安装后,Eclipse会提示重启以应用更改。 重启Eclipse后,我们会在"File" &gt; "New"菜单下看到"Dynamic Web ...

    Servlet&JSP学习笔记

    - **Apache Tomcat**: 是一种广泛使用的开源 Web 容器,支持 Java Servlet、JavaServer Pages (JSP) 和 Java WebSocket 技术。 ##### 1.2 Servlet 程序 - **实现机制**: - **Servlet 接口**: 定义了基本的行为...

Global site tag (gtag.js) - Google Analytics