基于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接口,实现如下:
创建网页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)!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

With the continuous development of Internet technology, real-time video streaming has become an important application in the Internet field. To achieve real-time video streaming, the key technologies include WebSocket and Java. This article will introduce how to use WebSocket and Java to implement real-time video streaming playback, and provide relevant code examples. 1. What is WebSocket? WebSocket is a protocol for full-duplex communication on a single TCP connection. It is used on the Web

With the continuous development of Internet technology, real-time communication has become an indispensable part of daily life. Efficient, low-latency real-time communication can be achieved using WebSockets technology, and PHP, as one of the most widely used development languages in the Internet field, also provides corresponding WebSocket support. This article will introduce how to use PHP and WebSocket to achieve real-time communication, and provide specific code examples. 1. What is WebSocket? WebSocket is a single

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

PHP and WebSocket: Best Practice Methods for Real-Time Data Transfer Introduction: In web application development, real-time data transfer is a very important technical requirement. The traditional HTTP protocol is a request-response model protocol and cannot effectively achieve real-time data transmission. In order to meet the needs of real-time data transmission, the WebSocket protocol came into being. WebSocket is a full-duplex communication protocol that provides a way to communicate full-duplex over a single TCP connection. Compared to H

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How does JavaWebsocket implement online whiteboard function? In the modern Internet era, people are paying more and more attention to the experience of real-time collaboration and interaction. Online whiteboard is a function implemented based on Websocket. It enables multiple users to collaborate in real-time to edit the same drawing board and complete operations such as drawing and annotation. It provides a convenient solution for online education, remote meetings, team collaboration and other scenarios. 1. Technical background WebSocket is a new protocol provided by HTML5. It implements

In this article, we will compare Server Sent Events (SSE) and WebSockets, both of which are reliable methods for delivering data. We will analyze them in eight aspects, including communication direction, underlying protocol, security, ease of use, performance, message structure, ease of use, and testing tools. A comparison of these aspects is summarized as follows: Category Server Sent Event (SSE) WebSocket Communication Direction Unidirectional Bidirectional Underlying Protocol HTTP WebSocket Protocol Security Same as HTTP Existing security vulnerabilities Ease of use Setup Simple setup Complex performance Fast message sending speed Affected by message processing and connection management Message structure Plain text or binary Ease of use Widely available Helpful for WebSocket integration
