Tomcat7中WebSocket初探
在HTML5中定义了WebSocket规范,该规范使得能够实现在页面中通过WebSocket协议和服务器进行双向通信。
在Web应用中一个常见的场景是Server端向Client端推送某些消息,要实现这项功能可以有一下方案:
(1) ajax技术+轮询 :这种方案仅仅是一个模拟实现,本质还是HTTP请求响应的模式,由于无法预期什么时候推送消息,造成很多无效的请求;
(2) 通过 flash之类 : 这种方式能够实现双向通信,但有一个前提条件就是依赖第三方插件,而在移动端浏览器大多数都不支持flash.
(3)WebSocket : 原生态支持真正的双向通信,有web TCP 之称,so easy.
1、建立WebSocket连接过程
关于WebSocket规范和协议参考 http://www.websocket.org/aboutwebsocket.html
这里简单描述一下:WebSocket协议一个设计原则就是能够和现有的Web方式一起工作,建立WebSocket连接是以HTTP连接开始,这个过程为 WebSocket握手 .
下图所示为一个WebSocket建立连接的请求和响应过程:
稍作解释如下:
- 浏览器向服务器发送一个 Upgrade 请求头,告诉服务器 “我想从 HTTP 协议 切换到 WebSocket 协议”;
- 服务器端接受请求,如果服务器支持 WebSocket ,则返回 Upgrade 响应头;
- 浏览器接受响应头,从这个时间点开始,由原来的HTTP协议转为 WebSocket协议,Websocket连接建立起来了.
WebSocket连接建立之后,数据传输通道 和端口使用的都是原来HTTP所使用的TCP/IP通道和端口 ,可以在浏览器和服务器之间进行全双工通信了。
数据帧 支持 text 和 binary 两种方式:在使用text方式传输时,以 0x00 为起始点,以0xFF结束,数据以UTF-8编码放在中间;对于 binary方式则没有结束标识,而是将数据帧长度置于数据前面。
2、浏览器端 WebSocket编程接口
首先需要检测浏览器是否支持WebSocket,代码如下:
var socket=null; window.WebSocket = window.WebSocket || window.MozWebSocket; if (!window.WebSocket) { alert(‘Error: WebSocket is not supported .‘); } else{ socket = new WebSocket(‘ws://...‘);}
Websocket接口定义如下:
interface WebSocket : EventTarget { readonly attribute DOMString url; // ready state const unsigned short CONNECTING = 0; const unsigned short OPEN = 1; const unsigned short CLOSING = 2; const unsigned short CLOSED = 3; readonly attribute unsigned short readyState; readonly attribute unsigned long bufferedAmount; // networking attribute EventHandler onopen; attribute EventHandler onerror; attribute EventHandler onclose; readonly attribute DOMString extensions; readonly attribute DOMString protocol; void close([Clamp] optional unsigned short code, optional DOMString reason); // messaging attribute EventHandler onmessage; attribute DOMString binaryType; void send(DOMString data); void send(Blob data); void send(ArrayBuffer data); void send(ArrayBufferView data); };从上面定义中可以很清晰的看出:
- 通过send()发送数据,
- 通过close()关闭连接,
- 通过注册事件函数onopen,onerror,onmessage,onclose来处理服响应。
3、服务器端WebSocket编程
这里以Tomcat 7 为例, 需要加载的依赖包为 \lib\catalina.jar、\lib\tomcat-coyote.jar
这里有两个重要的类 :WebSocketServlet 和 StreamInbound, 前者是一个容器,用来初始化WebSocket环境;后者是用来具体处理WebSocket请求和响应的。
编写一个Servlet类,继承自WebSocket,实现其抽象方法即可,代码如下:
package websocket; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.http.HttpServletRequest; import org.apache.catalina.websocket.StreamInbound; import org.apache.catalina.websocket.WebSocketServlet; public class HelloWebSocketServlet extends WebSocketServlet { private static final long serialVersionUID = 1L; private final AtomicInteger connectionIds = new AtomicInteger(0); @Override protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest request) { return new HelloMessageInbound(connectionIds.getAndIncrement(), request .getSession().getId()); } }
package websocket; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.nio.CharBuffer; import org.apache.catalina.websocket.StreamInbound; import org.apache.catalina.websocket.WsOutbound; public class HelloMessageInbound extends StreamInbound { private String WS_NAME; private final String FORMAT = "%s : %s"; private final String PREFIX = "ws_"; private String sessionId = ""; public HelloMessageInbound(int id, String _sessionId) { this.WS_NAME = PREFIX + id; this.sessionId = _sessionId; } @Override protected void onTextData(Reader reader) throws IOException { char[] chArr = new char[1024]; int len = reader.read(chArr); send(String.copyValueOf(chArr, 0, len)); } @Override protected void onClose(int status) { System.out.println(String.format(FORMAT, WS_NAME, "closing ......")); super.onClose(status); } @Override protected void onOpen(WsOutbound outbound) { super.onOpen(outbound); try { send("hello, my name is " + WS_NAME); send("session id = " + this.sessionId); } catch (IOException e) { e.printStackTrace(); } } private void send(String message) throws IOException { message = String.format(FORMAT, WS_NAME, message); System.out.println(message); getWsOutbound().writeTextMessage(CharBuffer.wrap(message)); } @Override protected void onBinaryData(InputStream arg0) throws IOException { } }
在Web.xml中进行Servlet配置:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>websocket demo</display-name> <servlet> <servlet-name>wsHello</servlet-name> <servlet-class>websocket.HelloWebSocketServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>wsHello</servlet-name> <url-pattern>/websocket/say</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
在index.jsp中编写浏览器端代码如下:
<!DOCTYPE HTML> <html> <head> <title>WebSocket demo</title> <style> body { padding: 40px;} #outputPanel{margin:10px;padding:10px; background:#eee; border:1px solid #000; min-height: 300px;} </style> </head> <body> <input type="text" id="messagebox" size="60" /> <input type="button" id="buttonSend" value="Send Message" /> <input type="button" id="buttonConnect" value="Connect to server" /> <input type="button" id="buttonClose" value="Disconnect" /> <br> <% out.println("Session ID = " + session.getId()); %> <div id="outputPanel"></div> </body> <script type="text/javascript"> var infoPanel = document.getElementById(‘outputPanel‘); var textBox = document.getElementById(‘messagebox‘); var sendButton = document.getElementById(‘buttonSend‘); var connButton = document.getElementById(‘buttonConnect‘); var discButton = document.getElementById(‘buttonClose‘); var console = { log : function(text) { infoPanel.innerHTML += text + "<br>"; } }; var demo = { socket : null, host : ‘‘, connect : function() { window.WebSocket = window.WebSocket || window.MozWebSocket; if (!window.WebSocket) { console.log(‘Error: WebSocket is not supported .‘); return; } this.socket = new WebSocket(this.host); this.socket.onopen = function() { console.log("websocket is opened ."); }; this.socket.onclose = function() { console.log("websocket is closed ."); demo.socket = null; }; this.socket.onmessage = function(message) { console.log(message.data); }; }, send : function(message) { if (this.socket) { this.socket.send(message); return true; } console.log(‘please connect to the server first !!!‘); return false; } }; demo.host = window.location.host + ‘/Hello/websocket/say‘; if (window.location.protocol == ‘http:‘) { demo.host = ‘ws://‘ + demo.host; } else { demo.host = ‘wss://‘ + demo.host; } sendButton.onclick = function() { var message = textBox.value; if (!message) return; if (!demo.send(message)) return; textBox.value = ‘‘; }; connButton.onclick = function() { if (!demo.socket) { demo.connect(); } else { console.log(‘websocket already exists .‘); } }; discButton.onclick = function() { if (demo.socket) { demo.socket.close(); } else { console.log(‘websocket is not found .‘); } }; </script> </html>
4、结果
这里看到 WebSocket建立的连接所访问的Session和HTTP访问的Session是一致的。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。