java實現websocket__web

來源:互聯網
上載者:User

websocket是什麼

websocket是一種基於TCP的網路通訊協定,實現了瀏覽器與伺服器的全雙工系統的通訊方式。協議包括一個開放的握手以及隨後TCP層上的訊息幀。

環境需要
Tomcat7以上,需要jar包:tomcat-websocket.jar和websocket-api.jar

前端實現

<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body>    <div id="info">        <button onClick="connect()">開啟串連</button>        <button onClick="closeWebSocket()">關閉串連</button>    </div><script src="js/jquery.min.js"></script><script>    var websocket = null;    var result;     //判斷當前瀏覽器是否支援WebSocket     function connect(){         //websocket目前狀態,0未串連,1已串連,2正在關閉串連,3串連已關閉或不可用         var websocketState = websocket?(websocket.readyState?websocket.readyState:0):0;         //如果當前已串連,則不再建立新的串連         if(websocketState !== 1){             if ('WebSocket' in window) {                var url = '';                if (window.location.protocol == 'http:') {                    url = 'ws://localhost:8080/mssm/websocket';                } else {                    url = 'wss://localhost:8080/mssm/websocket';                }                websocket = new WebSocket(url);               }               else {                   console.log('當前瀏覽器 Not support websocket')               }                //串連發生錯誤的回調方法                 websocket.onerror = function () {                     console.log("WebSocket串連發生錯誤,重新串連。。");                     connect();                 };                 //串連成功建立的回調方法                 websocket.onopen = function () {                    heartConnect.start();                    console.log("WebSocket串連成功");                 }                 //接收到訊息的回調方法                 websocket.onmessage = function (event) {                  result = event.data;                     console.log("接受回的訊息"+event.data);                 }                 //串連關閉的回調方法                 websocket.onclose = function () {                     console.log("WebSocket串連關閉");                 }         }else{             console.log('當前已經串連websocket,不會重複串連');         }     }     connect();     //監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket串連,防止串連還沒斷開就關閉視窗,server端會拋異常。      window.onbeforeunload = function () {          closeWebSocket();      }     //關閉WebSocket串連      function closeWebSocket() {          heartConnect.close();          websocket.close();      }      //發送訊息      function send() {          var message = "this is a message from client";          websocket.send(message);      }      var heartConnect = {             timeOut:6000,             timeOutObj:null,             start:function(){                 this.timeOutObj = setTimeout(function(){                     var websocketState = websocket?(websocket.readyState?websocket.readyState:0):0;                     if(websocketState===1){                         console.log('websocket串連正常,重設心跳');                         clearTimeout(this.timeOutObj);                         heartConnect.start();                     }else{                         console.log('websocket串連失敗,重新串連。。');                         connect();                     }                 },this.timeOut);             },             close:function(){                 clearTimeout(this.timeOutObj);             }                 }</script></body></html>

java實現

@ServerEndpoint("/websocket")public class WebSocketController {    //靜態變數,用來記錄當前線上串連數。安全執行緒。    private static AtomicInteger onlineCount = new AtomicInteger(0);    //concurrent包的安全執行緒Map,用來存放每個用戶端對應的MyWebSocket對象    private static ConcurrentHashMap<String,WebSocketController> webSocketMap = new ConcurrentHashMap<String, WebSocketController>();    //與某個用戶端的串連會話,需要通過它來給用戶端發送資料    private Session session;    /**     * 串連建立成功調用的方法     * @param session  可選的參數。session為與某個用戶端的串連會話,需要通過它來給用戶端發送資料     */    @OnOpen    public void onOpen(Session session){        this.session = session;        webSocketMap.put(session.getId(), this);        addOnlineCount();           //線上數加1        System.out.println("有新串連加入。當前線上人數為" + getOnlineCount());    }    /**     * 串連關閉調用的方法     */    @OnClose    public void onClose(){        webSocketMap.remove(this.session.getId());        subOnlineCount();           //線上數減1        System.out.println("有一串連關閉。當前線上人數為" + getOnlineCount());    }    /**     * 收到用戶端訊息後調用的方法     * @param message 用戶端發送過來的訊息     * @param session 可選的參數     */    @OnMessage    public void onMessage(String message, Session session) {        System.out.println("來自用戶端的訊息:" + message);        //群發訊息        for(String key:webSocketMap.keySet()){            try{                webSocketMap.get(key).sendMessage("你的id為:"+key);            }catch(IOException e){                e.printStackTrace();                continue;            }        }    }    /**     * 發生錯誤時調用     * @param session     * @param error     */    @OnError    public void onError(Session session, Throwable error){        System.out.println("發生錯誤");        error.printStackTrace();    }    /**     * 這個方法與上面幾個方法不一樣。沒有用註解,是根據自己需要添加的方法。     * @param message     * @throws IOException     */    public void sendMessage(String message) throws IOException{        this.session.getBasicRemote().sendText(message);        //this.session.getAsyncRemote().sendText(message);    }    public static synchronized int getOnlineCount() {        return onlineCount.get();    }    public static synchronized void addOnlineCount() {        //將原子變數+1        WebSocketController.onlineCount.getAndIncrement();    }    public static synchronized void subOnlineCount() {        WebSocketController.onlineCount.getAndDecrement();    }}

項目地址:https://github.com/Xchunguang/xuchg

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.