WebSocket協議是基於TCP的一種新的網絡協議。javascript
它實現了瀏覽器與服務器全雙工(full-duplex)通訊,容許服務器主動發送信息給客戶端。html
實時Web應用的解決方案,實現Web的實時通訊。java
說的再直白點,html的消息推送。jquery
假如你有一個頁面,數據不按期更改,一般的作法就是輪詢,客戶端不停地向服務器請求最新的數據。git
當有了web socket,數據變更時 讓服務器通知客戶端,啓不是很美妙?github
(1) 默認端口是80和443(ssl)。web
(2) 協議標識符是ws和ws(ssl)。api
(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
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) { //... } }
這裏使用了 觀察者模式,對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()); }
普通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--