search
HomeWeb Front-endH5 Tutorial基于Tomcat运行HTML5 WebSocket echo实例详解

基于Tomcat运行HTML5 WebSocket echo实例详解

 

  一、概述

 

  作为HTML5新特性之一的WebSocket组件,在实时性有一定要求的WEB应用开发中还是有一定用武之地,高版本的IE、Chrome、FF浏览器都支持Websocket,标准的Websocket通信是基于RFC6455实现服务器端与客户端握手与消息接发的。如果对Websocket通信不是太理解,可以查看RFC文档即可,简单说就是通过发送HTTP请求,实现双方握手,将无状态的HTTP通信协议进一步升级成有状态的通信协议,同时Websocket还支持子协议选项与安全传输。标准的websocket连接URL以ws开头,如果是基于TLS的则以wss开头。基于Websocket可以很方便的开发基于web聊天程序,各种网页消息通知与推送通知。

 

  如果非要扒一扒Websocket的今生前世的话,还记得最早的基于HTTP轮询实现网页即时通信的方式,那种做法比较消耗资源、于是有人改进了编程CometD长连接方式,可是本质上还是换汤不换药,而websocket的出现正好解决了这些问题,但是很多浏览器的低版本还是不支持websocket,于是还催生了一些基于websocket理念实现的JS通信框架,其中学得比较像的有SockJS与socket.io,他们都号称支持websocket,然后如果浏览器端不支持原生的websocket,它们会自动启用fallback选项使用其它诸如ajax、Http轮询、长轮询/连接、甚至是flash的socket等机制实现模拟websocket的工作方式,但是他们最大的弊端是如果客户端使用了这些框架,服务器必须用它们,否则等待开发者就是一大堆无法回避的问题,同时很多都是无解的。主要原因在于它们实现自己的协议集,不照它们的格式处理数据没法玩。闲话说的有点多。

 

  二、实现步骤

 

  Tomcat7的高版本中实现了Websocket服务器端RFC6455标准协议,可以跟浏览器端websocket进行通信,首先要做好如下几步:

 

  1.安装高版本JDK – JDK8

  2.安装Tomcat 7.0.64

  3.在eclipse中建立一个动态的web项目

 

  根据JSR标准,Java中实现websocket的标准接口可以基于注解方式,tomcat也搞好了,只有我们实现如下代码,即可创建一个websocket回声服务器:

package com.websocket.demo;  
   
import java.io.IOException;  
import java.nio.ByteBuffer;  
   
import javax.websocket.OnMessage;  
import javax.websocket.OnOpen;  
import javax.websocket.Session;  
import javax.websocket.server.ServerEndpoint;  
   
@ServerEndpoint(value = "/echo")  
public class EchoExample {  
       
    @OnMessage  
    public void echoTextMessage(Session session, String msg, boolean last) {  
        try {  
            if (session.isOpen()) {  
                System.out.println("received from client message = " + msg);  
                session.getBasicRemote().sendText(msg, last);  
            }  
        } catch (IOException e) {  
            try {  
                session.close();  
            } catch (IOException e1) {  
            }  
        }  
    }  
       
    @OnOpen  
    public void openConn(Session session) throws IOException {  
        session.getBasicRemote().sendText("hello web socket"); // means open it  
    }  
       
    @OnMessage  
    public void echoBinaryMessage(Session session, ByteBuffer bb, boolean last) {  
        System.out.println("send binary message...");  
        try {  
            if (session.isOpen()) {  
                System.out.println("byte buffer lenghth : " + bb.array().length);  
                System.out.println("byte buffer content: " + ((bb.array()[0]) & 0xff));  
                System.out.println("byte buffer content: " + ((bb.array()[1]) & 0xff));  
                System.out.println("byte buffer content: " + ((bb.array()[2]) & 0xff));  
                session.getBasicRemote().sendBinary(bb, last);  
            }  
        } catch (IOException e) {  
            try {  
                session.close();  
            } catch (IOException e1) {  
                // Ignore  
            }  
        }  
    }  
   
}


  如何在tomcat中启动websocket服务器,首先需要在web.xml添加如下配置:

[listener]  
    [listener-class]org.apache.tomcat.websocket.server.WsContextListener[/listener-class]  
[/listener]


  然后实现ServerApplicationConfig接口,实现如下:

基于Tomcat运行HTML5 WebSocket echo实例详解

  创建网页echo.html,内容如下:

[html] 
[head] 
[title>Web Socket Echo Test[/title] 
[script] 
        var ws = null;  
        var count = 0;  
        function setConnected(connected) {  
            document.getElementById('connect').disabled = connected;  
            document.getElementById('disconnect').disabled = !connected;  
            document.getElementById('echo').disabled  = !connected;  
        }  
   
        function connect() {  
            var target = document.getElementById('target').value;  
            if (target == '') {  
                alert('Please select server side connection implementation.');  
                return;  
            }  
   
            if ('WebSocket' in window) {  
                ws = new WebSocket(target);  
            } else if ('MozWebSocket' in window) {  
                ws = new MozWebSocket(target);  
            } else {  
                alert('WebSocket is not supported by this browser.');  
                return;  
            }  
               
            ws.onopen = function () {  
                setConnected(true);  
                log('Info: WebSocket connection opened.');  
            };  
            ws.onmessage = function (event) {  
                log('Received: ' + event.data);

  

以上就是基于Tomcat运行HTML5 WebSocket echo实例详解的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Mastering Microdata: A Step-by-Step Guide for HTML5Mastering Microdata: A Step-by-Step Guide for HTML5May 14, 2025 am 12:07 AM

MicrodatainHTML5enhancesSEOanduserexperiencebyprovidingstructureddatatosearchengines.1)Useitemscope,itemtype,anditempropattributestomarkupcontentlikeproductsorevents.2)TestmicrodatawithtoolslikeGoogle'sStructuredDataTestingTool.3)ConsiderusingJSON-LD

What's New in HTML5 Forms? Exploring the New Input TypesWhat's New in HTML5 Forms? Exploring the New Input TypesMay 13, 2025 pm 03:45 PM

HTML5introducesnewinputtypesthatenhanceuserexperience,simplifydevelopment,andimproveaccessibility.1)automaticallyvalidatesemailformat.2)optimizesformobilewithanumerickeypad.3)andsimplifydateandtimeinputs,reducingtheneedforcustomsolutions.

Understanding H5: The Meaning and SignificanceUnderstanding H5: The Meaning and SignificanceMay 11, 2025 am 12:19 AM

H5 is HTML5, the fifth version of HTML. HTML5 improves the expressiveness and interactivity of web pages, introduces new features such as semantic tags, multimedia support, offline storage and Canvas drawing, and promotes the development of Web technology.

H5: Accessibility and Web Standards ComplianceH5: Accessibility and Web Standards ComplianceMay 10, 2025 am 12:21 AM

Accessibility and compliance with network standards are essential to the website. 1) Accessibility ensures that all users have equal access to the website, 2) Network standards follow to improve accessibility and consistency of the website, 3) Accessibility requires the use of semantic HTML, keyboard navigation, color contrast and alternative text, 4) Following these principles is not only a moral and legal requirement, but also amplifying user base.

What is the H5 tag in HTML?What is the H5 tag in HTML?May 09, 2025 am 12:11 AM

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

H5 Code: A Beginner's Guide to Web StructureH5 Code: A Beginner's Guide to Web StructureMay 08, 2025 am 12:15 AM

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

H5 Code Structure: Organizing Content for ReadabilityH5 Code Structure: Organizing Content for ReadabilityMay 07, 2025 am 12:06 AM

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.