Java Websocket例項
記錄下自己在用的websocket
介紹
現在很多網站為了實現即時通訊,所用的技術都是輪詢(polling)。輪詢是在特定的的時間間隔(如每1秒),
由瀏覽器對伺服器發出HTTP request,然後由伺服器返回最新的資料給客服端的瀏覽器。
這種傳統的HTTP request 的模式帶來很明顯的缺點 – 瀏覽器需要不斷的向伺服器發出請求,
然而HTTP request 的header是非常長的,裡面包含的資料可能只是一個很小的值,這樣會佔用很多的頻寬。
而最比較新的技術去做輪詢的效果是Comet – 用了AJAX。但這種技術雖然可達到全雙工通訊,但依然需要發出請求。
在 WebSocket API,瀏覽器和伺服器只需要要做一個握手的動作,然後,瀏覽器和伺服器之間就形成了一條快速通道。兩者之間就直接可以資料互相傳送。
執行環境:
客戶端
實現了websocket的瀏覽器
Chrome | Supported in version 4+ |
Firefox | Supported in version 4+ |
Internet Explorer | Supported in version 10+ |
Opera | Supported in version 10+ |
Safari | Supported in version 5+ |
服務端
依賴
Tomcat 7.0.47以上 + J2EE7
<dependency> |
注意:早前業界沒有統一的標準,各伺服器都有各自的實現,現在J2EE7的JSR356已經定義了統一的標準,請儘量使用支援最新通用標準的伺服器。
ps:最早我們是用的Tomcat 7自帶的實現,後來要升級Tomcat 8,結果原來的實現方式在Tomcat 8不支援了,就只好切換到支援Websocket 1.0版本的Tomcat了。
主流的java web伺服器都有支援JSR365標準的版本了,請自行Google。
用nginx做反向代理的需要注意啦,socket請求需要做特殊配置的,切記!
Tomcat的處理方式建議修改為NIO的方式,同時修改連線數到合適的引數,請自行Google!
服務端不需要在web.xml中做額外的配置,Tomcat啟動後就可以直接連線了。
實現
import com.dooioo.websocket.utils.SessionUtils; |
工具類用來儲存唯一key和連線
這個是我業務的需要,我的業務是伺服器有對應動作觸發時,推送資料到客戶端,沒有接收客戶端資料的操作。
import javax.websocket.Session; |
推送資料到客戶端
在其他業務方法中呼叫
|
我是使用非同步的方法推送資料,還有同步的方法
客戶端程式碼
var webSocket = null; |
其他除錯工具
Java實現一個websocket的客戶端
依賴:
|
程式碼:
|
|