詳解Tomcat7中WebSocket初探
HTML5中定義了WebSocket規(guī)范,該規(guī)范使得能夠?qū)崿F(xiàn)在瀏覽器端和服務(wù)器端通過WebSocket協(xié)議進(jìn)行雙向通信。
在Web應(yīng)用中一個(gè)常見的場景是Server端向Client端推送某些消息,要實(shí)現(xiàn)這項(xiàng)功能,按照傳統(tǒng)的思路可以有以下可選方案:
- Ajax + 輪詢 :這種方案僅僅是一個(gè)模擬實(shí)現(xiàn),本質(zhì)還是HTTP請(qǐng)求響應(yīng)的模式,由于無法預(yù)期什么時(shí)候推送消息,造成很多無效的請(qǐng)求;
- 通過 Flash等第三方插件 :這種方式能夠?qū)崿F(xiàn)雙向通信,但有一個(gè)前提條件就是依賴第三方插件,而在移動(dòng)端瀏覽器大多數(shù)都不支持Flash.
隨著Html5技術(shù)的普及,主流瀏覽器對(duì)HTML5標(biāo)準(zhǔn)的支持越來越好,利用瀏覽器原生支持WebSocket就可以輕松的實(shí)現(xiàn)上面的功能。只需要在瀏覽器端和服務(wù)器端建立一條WebSocket連接,就可以進(jìn)行雙向同時(shí)傳遞數(shù)據(jù)。相比于傳統(tǒng)的方式,使用WebSocket的優(yōu)點(diǎn)顯而易見了:
- 主動(dòng)的雙向通信模式:相對(duì)于使用Ajax的被動(dòng)的請(qǐng)求響應(yīng)模式,主動(dòng)模式下可以節(jié)省很多無意義的請(qǐng)求;
- 瀏覽器原生支持:簡化了編程環(huán)境和用戶環(huán)境,不依賴第三方插件;
- 高效省流量:以數(shù)據(jù)幀的方式進(jìn)行傳輸,拋棄了HTTP協(xié)議中請(qǐng)求頭,直接了當(dāng).
那么在實(shí)際中如何建立WebSocket連接?在瀏覽器端和服務(wù)器端如何針對(duì)WebSocket編程?
就此問題,下文描述了建立WebSocket連接的過程,瀏覽器端WebSocket接口,并以Tomcat 7 為例在服務(wù)器端編寫WebSocket服務(wù)。
1. 建立WebSocket連接過程
關(guān)于WebSocket規(guī)范和協(xié)議參考 http://www.websocket.org/aboutwebsocket.html
設(shè)計(jì)WebSocket協(xié)議的一個(gè)重要原則就是能和現(xiàn)有的Web方式和諧共處,建立WebSocket連接是以HTTP請(qǐng)求響應(yīng)為基礎(chǔ)的,這個(gè)過程為 WebSocket握手 .
圖下所示為一個(gè)WebSocket建立連接的請(qǐng)求和響應(yīng)過程:

此處稍作解釋一下:
- 瀏覽器向服務(wù)器發(fā)送一個(gè) Upgrade 請(qǐng)求頭,告訴服務(wù)器 “我想從 HTTP 協(xié)議 切換到 WebSocket 協(xié)議”;
- 服務(wù)器端收到請(qǐng)求,如果支持 WebSocket ,則返回pUpgrade響應(yīng)頭,表示“我支持WebSocket協(xié)議,可以切換”;
- 瀏覽器接收響應(yīng)頭,從原來的HTTP協(xié)議切換WebSocket協(xié)議,WebSocket連接建立起來.
WebSocket連接建立在原來HTTP所使用的TCP/IP通道和端口之上 ,也就是說原來使用的是8080端口,現(xiàn)在還是使用8080端口,而不是使用新的TCP/IP連接。
數(shù)據(jù)幀傳輸支持Text和Binary兩種方式:在使用Text方式時(shí),以0x00為起始點(diǎn),以0xFF結(jié)束,數(shù)據(jù)以UTF-8編碼置于中間;對(duì)于Binary方式則沒有結(jié)束標(biāo)識(shí),而是將數(shù)據(jù)幀長度置于數(shù)據(jù)前面。
2. 瀏覽器端 WebSocket編程接口
在瀏覽器端使用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()發(fā)向服務(wù)器送數(shù)據(jù);
- 通過close()關(guān)閉連接;
- 通過注冊(cè)事件函數(shù) onopen,onerror,onmessage,onclose 來處理服響應(yīng).
在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'); // 輸出結(jié)果面板
var textBox = document.getElementById('messagebox'); // 消息輸入框
var sendButton = document.getElementById('buttonSend'); // 發(fā)送消息按鈕
var connButton = document.getElementById('buttonConnect');// 建立連接按鈕
var discButton = document.getElementById('buttonClose');// 斷開連接按鈕
// 控制臺(tái)輸出對(duì)象
var console = {log : function(text) {infoPanel.innerHTML += text + "<br>";}};
// WebSocket演示對(duì)象
var demo = {
socket : null, // WebSocket連接對(duì)象
host : '', // WebSocket連接 url
connect : function() { // 連接服務(wù)器
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) { // 檢測瀏覽器支持
console.log('Error: WebSocket is not supported .');
return;
}
this.socket = new WebSocket(this.host); // 創(chuàng)建連接并注冊(cè)響應(yīng)函數(shù)
this.socket.onopen = function(){console.log("websocket is opened .");};
this.socket.onmessage = function(message) {console.log(message.data);};
this.socket.onclose = function(){
console.log("websocket is closed .");
demo.socket = null; // 清理
};
},
send : function(message) { // 發(fā)送消息方法
if (this.socket) {
this.socket.send(message);
return true;
}
console.log('please connect to the server first !!!');
return false;
}
};
// 初始化WebSocket連接 url
demo.host=(window.location.protocol == 'http:') ? 'ws://' : 'wss://' ;
demo.host += window.location.host + '/Hello/websocket/say';
// 初始化按鈕點(diǎn)擊事件函數(shù)
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>
3. 服務(wù)器端WebSocket編程
Tomcat 7提供了WebSocket支持,這里就以Tomcat 7 為例,探索一下如何在服務(wù)器端進(jìn)行WebSocket編程。需要加載的依賴包為 \lib\catalina.jar、\lib\tomcat-coyote.jar
這里有兩個(gè)重要的類 :WebSocketServlet 和 StreamInbound, 前者是一個(gè)容器,用來初始化WebSocket環(huán)境;后者是用來具體處理WebSocket請(qǐng)求和響應(yīng)的。
編寫一個(gè)Servlet類,繼承自WebSocket,實(shí)現(xiàn)其抽象方法即可,代碼如下:
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中進(jìn)行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>
4. 結(jié)果


這里看到 WebSocket建立的連接所訪問的Session和HTTP訪問的Session是一致的。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Tomcat怎么實(shí)現(xiàn)異步Servlet
- 詳解Tomcat集群如何同步會(huì)話
- tomcat中Servlet對(duì)象池介紹及如何使用
- tomcat中Servlet的工作機(jī)制詳細(xì)介紹
- Tomcat 檢測內(nèi)存泄漏實(shí)例詳解
- Tomcat 部署程序方法步驟
- 詳解Java的環(huán)境變量和Tomcat服務(wù)器配置
- Tomcat 日志切割(logrotate)詳細(xì)介紹
- CentOS系統(tǒng)下安裝Tomcat7的過程詳解
- 基于Tomcat7、Java、WebSocket的服務(wù)器推送聊天室實(shí)例
- tomcat自定義Web部署文件中docBase和workDir的區(qū)別介紹
- 詳解Tomcat如何實(shí)現(xiàn)Comet
- Tomcat 熱部署的實(shí)現(xiàn)原理詳解
相關(guān)文章
Tomcat啟動(dòng)報(bào)錯(cuò)子容器啟動(dòng)失敗問題及解決
這篇文章主要介紹了Tomcat啟動(dòng)報(bào)錯(cuò)子容器啟動(dòng)失敗問題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
Tomcat注冊(cè)成服務(wù)的幾個(gè)注意點(diǎn)小結(jié)
這篇文章主要介紹了Tomcat注冊(cè)成服務(wù)的幾個(gè)注意點(diǎn),本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
Tomcat默認(rèn)程序發(fā)布路徑的使用與修改方法講解
今天小編就為大家分享一篇關(guān)于Tomcat默認(rèn)程序發(fā)布路徑的使用與修改方法講解,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-02-02
怎么減少本地調(diào)試tomcat重啟次數(shù)你知道嗎
這篇文章主要為大家詳細(xì)介紹了怎么減少本地調(diào)試tomcat重啟次數(shù),使用Groovy,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01
Maven 修改tomcat運(yùn)行版本和端口的實(shí)現(xiàn)方法
今天小編就為大家分享一篇Maven 修改tomcat運(yùn)行版本和端口的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-05-05

