websocket簡單一實例

來源:互聯網
上載者:User

標籤:online   ssi   host   str   註解   vax   javascrip   用戶端   簡單的   

只需要兩個檔案即可,一個服務端,一個前端,一下樣本為類比簡單的聊天程式:

服務端:

package com.test.websocket;import java.io.IOException;import java.util.concurrent.CopyOnWriteArraySet;import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;@ServerEndpoint("/chat")public class MyWebSocket {        //靜態變數,用來記錄當前線上串連數。應該把它設計成安全執行緒的。    private static int onlineCount = 0;         //concurrent包的安全執行緒Set,用來存放每個用戶端對應的MyWebSocket對象。若要實現服務端與單一用戶端通訊的話,可以使用Map來存放,其中Key可以為使用者標識    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();         //與某個用戶端的串連會話,需要通過它來給用戶端發送資料    private Session session;         /**     * 串連建立成功調用的方法     * @param session  可選的參數。session為與某個用戶端的串連會話,需要通過它來給用戶端發送資料     */    @OnOpen    public void onOpen(Session session){        this.session = session;        webSocketSet.add(this);     //加入set中        addOnlineCount();           //線上數加1        System.out.println("有新串連加入!當前線上人數為" + getOnlineCount());    }         /**     * 串連關閉調用的方法     */    @OnClose    public void onClose(){        webSocketSet.remove(this);  //從set中刪除        subOnlineCount();           //線上數減1            System.out.println("有一串連關閉!當前線上人數為" + getOnlineCount());    }         /**     * 收到用戶端訊息後調用的方法     * @param message 用戶端發送過來的訊息     * @param session 可選的參數     */    @OnMessage    public void onMessage(String message, Session session) {        System.out.println("來自用戶端的訊息:" + message);                 //群發訊息        for(MyWebSocket item: webSocketSet){                         try {                item.sendMessage(message);            } 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;    }     public static synchronized void addOnlineCount() {        MyWebSocket.onlineCount++;    }         public static synchronized void subOnlineCount() {        MyWebSocket.onlineCount--;    }    }

前端:

<html><body>    Welcome<br/>    <input id="text" type="text" />    <button onclick="send()">Send</button>    <button onclick="closeWebSocket()">Close</button>    <div id="message"></div>    </body><script type="text/JavaScript">      var websocket = null;            //判斷當前瀏覽器是否支援WebSocket      if(‘WebSocket‘ in window){          websocket = new WebSocket("ws://localhost:8072/worktest/chat");      }      else{          alert(‘Not support websocket‘);      }          //串連發生錯誤的回調方法      websocket.onerror = function(){          setMessageInnerHTML("error");      };           //串連成功建立的回調方法      websocket.onopen = function(event){          setMessageInnerHTML("open");      };            //接收到訊息的回調方法      websocket.onmessage = function(){          setMessageInnerHTML(event.data);      };           //串連關閉的回調方法      websocket.onclose = function(){          setMessageInnerHTML("close");      };             //監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket串連,防止串連還沒斷開就關閉視窗,server端會拋異常。      window.onbeforeunload = function(){          websocket.close();      };             //將訊息顯示在網頁上      function setMessageInnerHTML(innerHTML){          document.getElementById(‘message‘).innerHTML += innerHTML + ‘<br/>‘;      }       //關閉串連      function closeWebSocket(){          websocket.close();      }        //發送訊息      function send(){          var message = document.getElementById(‘text‘).value;          websocket.send(message);      }  </script></html>

 

websocket簡單一實例

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.