一、概述
作为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接口,实现如下:
创建网页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)!

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.