# web socket是什么?
WebSocket協議是基於TCP的一種新的網絡協議。
它實現了瀏覽器與服務器全雙工(full-duplex)通信,允許服務器主動發送信息給客戶端。
## 用途
實時Web應用的解決方案,實現Web的實時通信。
說的再直白點,html的消息推送。
假如你有一個頁面,數據不定期更改,通常的做法就是輪詢,客戶端不停地向服務器請求最新的數據。
當有了web socket,數據變動時 讓服務器通知客戶端,啟不是很美妙?
## 請求示例
(1) 默認端口是80和443(ssl)。
(2) 協議標識符是ws和ws(ssl)。
(3) 請求報文示例

General -------------------------------------------- Request URL:ws://localhost:8080/j2ee-websocket/websocket/1 Request Method:GET Status Code:101 Switching Protocols --------------------------------------------- Response Headers --------------------------------------------- Connection:upgrade Date:Tue, 05 Dec 2017 01:22:45 GMT Sec-WebSocket-Accept:cRxT/XcOpnsleDb1KdydWXOw+us= Sec-WebSocket-Extensions:permessage-deflate;client_max_window_bits=15 Server:Apache-Coyote/1.1 Upgrade:websocket
# 代碼實現
代碼分為3個部分:javax.websocket api實現,使用觀察者模式增強,google/jquery-websocket代碼庫。
完整代碼地址,開箱即用。github:j2ee-websocket
## 服務端 java代碼
jar -- 引入javax.websocket,或引入javaee-api。
這里只展示api接口特性。
/** *Web Socket api implement *參數以URL路徑參數傳遞 */ @ServerEndpoint(value = "/websocket/{principal}") public class DefaultWebSocket { /** Web Socket連接建立成功的回調方法 */ @OnOpen public void onOpen(@PathParam("principal") String principal, Session session) {
//... } /** 服務端收到客戶端發來的消息 */ @OnMessage public void onMessage(@PathParam("principal") String principal, String message, Session session) { //... } @OnClose public void onClose(@PathParam("principal") String principal, Session session) {
//... } @OnError public void onError(@PathParam("principal") String principal, Session session, Throwable error) { //... } }
## 服務端推送消息至客戶端 java代碼
這里使用了 觀察者模式,對websocket進行了增強,詳見完整代碼:github:j2ee-websocket。
/**服務端向客戶端推送消息*/ public void notifyTest() { String principal = "1"; String type = "radio"; JSONObject data = new JSONObject(); data.put("title", "test web socket"); data.put("content", "Have you recieve this msg?--this msg from server."); WebSocketSubject subject = WebSocketSubject.Holder.getSubject(principal); subject.notify(type, data.toJSONString()); }
## 客戶端 javascript代碼
普通js代碼

<script type="text/javascript"> var websocket = null; var principal = '1'; var socketURL = 'ws://' + window.location.host + '/j2ee-websocket/websocket/' + principal; //判斷當前瀏覽器是否支持WebSocket if('WebSocket' in window){ websocket = new WebSocket(socketURL); } else{ alert('Not support websocket'); } //連接發生錯誤的回調方法 websocket.onerror = function(event){ alert("error"); }; //連接成功建立的回調方法 websocket.onopen = function(){ alert("open"); } //接收到消息的回調方法 websocket.onmessage = function(event){ alert('recive : ' + event.data); } //連接關閉的回調方法 websocket.onclose = function(event){ alert("close"); } //發送消息 function send(message){ websocket.send(message); } </script>
推薦:google/jquery-websocket代碼 (http://code.google.com/p/jquery-websocket)
google/jquery-websocket增加了消息的類型,將消息拆分為{"type":"","message":""}。
這樣更靈活,可以根據業務類型,定義type,如:通知,公告,廣播,發文等...
<script type="text/javascript"> var principal = '1'; var socketURL = 'ws://' + window.location.host + '/j2ee-websocket/websocket/' + principal; websocket = $.websocket(socketURL, { open : function() { // when the socket opens alert("open"); }, close : function() { // when the socket closes alert("close"); }, //收到服務端推送的消息處理 events : { 'radio' : function(event) { console.info($.parseJSON(event.data)); }, 'notice' : function(event) { console.info($.parseJSON(event.data)); }, //... more custom type of message } }); //發送消息 function send() { websocket.send('radio', " hello,this msg from client request"); } </script>
# 客戶端運行示例
--END--