WebSocket的使用

首先先了解一下wbsocket是什麼?

一.WebSocket簡單介紹

  隨着互聯網的發展,傳統的HTTP協議已經很難滿足Web應用日益複雜的需求了。近年來,隨着HTML5的誕生,WebSocket協議被提出,它實現了瀏覽器與服務器的全雙工通信,擴展了瀏覽器與服務端的通信功能,使服務端也能主動向客戶端發送數據。

  我們知道,傳統的HTTP協議是無狀態的,每次請求(request)都要由客戶端(如 瀏覽器)主動發起,服務端進行處理後返回response結果,而服務端很難主動向客戶端發送數據;這種客戶端是主動方,服務端是被動方的傳統Web模式 對於信息變化不頻繁的Web應用來說造成的麻煩較小,而對於涉及實時信息的Web應用卻帶來了很大的不便,如帶有即時通信、實時數據、訂閱推送等功能的應 用。在WebSocket規範提出之前,開發人員若要實現這些實時性較強的功能,經常會使用折衷的解決方法:輪詢(polling)Comet技術。其實後者本質上也是一種輪詢,只不過有所改進。

  輪詢是最原始的實現實時Web應用的解決方案。輪詢技術要求客戶端以設定的時間間隔週期性地向服務端發送請求,頻繁地查詢是否有新的數據改動。明顯地,這種方法會導致過多不必要的請求,浪費流量和服務器資源。

  Comet技術又可以分爲長輪詢流技術長輪詢改進了上述的輪詢技術,減小了無用的請求。它會爲某些數據設定過期時間,當數據過期後纔會向服務端發送請求;這種機制適合數據的改動不是特別頻繁的情況。流技術通常是指客戶端使用一個隱藏的窗口與服務端建立一個HTTP長連接,服務端會不斷更新連接狀態以保持HTTP長連接存活;這樣的話,服務端就可以通過這條長連接主動將數據發送給客戶端;流技術在大併發環境下,可能會考驗到服務端的性能。

  這兩種技術都是基於請求-應答模式,都不算是真正意義上的實時技術;它們的每一次請求、應答,都浪費了一定流量在相同的頭部信息上,並且開發複雜度也較大。

  伴隨着HTML5推出的WebSocket,真正實現了Web的實時通信,使B/S模式具備了C/S模式的實時通信能力。WebSocket的工作流程是這 樣的:瀏覽器通過JavaScript向服務端發出建立WebSocket連接的請求,在WebSocket連接建立成功後,客戶端和服務端就可以通過 TCP連接傳輸數據。因爲WebSocket連接本質上是TCP連接,不需要每次傳輸都帶上重複的頭部數據,所以它的數據傳輸量比輪詢和Comet技術小 了很多。本文不詳細地介紹WebSocket規範,主要介紹下WebSocket在Java Web中的實現。

  JavaEE 7中出了JSR-356:Java API for WebSocket規範。不少Web容器,如Tomcat,Nginx,Jetty等都支持WebSocket。Tomcat從7.0.27開始支持 WebSocket,從7.0.47開始支持JSR-356,下面的Demo代碼也是需要部署在Tomcat7.0.47以上的版本才能運行。


請重點記住使用websocket項目最低使用Tomcat7 ,jdk1.7

所需要使用的架包,如果你是maven項目:

  
<dependency>      <groupId>javax.servlet</groupId>      <artifactId>javax.servlet-api</artifactId>      <version>3.1.0</version>  </dependency>  <dependency>      <groupId>com.fasterxml.jackson.core</groupId>      <artifactId>jackson-core</artifactId>      <version>2.3.0</version>  </dependency>  <dependency>      <groupId>com.fasterxml.jackson.core</groupId>      <artifactId>jackson-databind</artifactId>      <version>2.3.0</version>  </dependency>  <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-websocket</artifactId>     <version>4.0.1.RELEASE</version>  </dependency>  <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-messaging</artifactId>     <version>4.0.1.RELEASE</version>  </dependency> 


spring.xml

  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.        xmlns:websocket="http://www.springframework.org/schema/websocket"  
  4.        xsi:schemaLocation="  
  5.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  6.         http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd"> 


更新spring框架的jar包至4.0以上(spring-core, spring-context, spring-web and spring-webmvc)

  1. <dependency>  
  2. <span style="white-space:pre">    </span><groupId>org.springframework</groupId>  
  3.     <artifactId>spring-core</artifactId>  
  4.     <version>${spring.version}</version>  
  5. </dependency>  
  6. <dependency>  
  7.     <groupId>org.springframework</groupId>  
  8.     <artifactId>spring-web</artifactId>  
  9.     <version>${spring.version}</version>  
  10. </dependency>  
  11. <dependency>  
  12.     <groupId>org.springframework</groupId>  
  13.     <artifactId>spring-webmvc</artifactId>  
  14.     <version>${spring.version}</version>  
  15. </dependency>  
  16. <dependency>  
  17.     <groupId>org.springframework</groupId>  
  18.     <artifactId>spring-context-support</artifactId>  
  19.     <version>${spring.version}</version>  
  20. </dependency> 

 
  

服務器端:

  1. package com.Socket;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.Map;  
  5. import java.util.concurrent.ConcurrentHashMap;  
  6. import javax.websocket.*;  
  7. import javax.websocket.server.PathParam;  
  8. import javax.websocket.server.ServerEndpoint;  
  9. import net.sf.json.JSONObject;  
  10.   
  11. @ServerEndpoint("/websocket/{username}")  
  12. public class WebSocket {  
  13.   
  14.     private static int onlineCount = 0;  
  15.     private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();  
  16.     private Session session;  
  17.     private String username;  
  18.       
  19.     @OnOpen  
  20.     public void onOpen(@PathParam("username") String username, Session session) throws IOException {  
  21.   
  22.         this.username = username;  
  23.         this.session = session;  
  24.           
  25.         addOnlineCount();  
  26.         clients.put(username, this);  
  27.         System.out.println("已連接");  
  28.     }  
  29.   
  30.     @OnClose  
  31.     public void onClose() throws IOException {  
  32.         clients.remove(username);  
  33.         subOnlineCount();  
  34.     }  
  35.   
  36.     @OnMessage  
  37.     public void onMessage(String message) throws IOException {  
  38.   
  39.         JSONObject jsonTo = JSONObject.fromObject(message);  
  40.           
  41.         if (!jsonTo.get("To").equals("All")){  
  42.             sendMessageTo("給一個人", jsonTo.get("To").toString());  
  43.         }else{  
  44.             sendMessageAll("給所有人");  
  45.         }  
  46.     }  
  47.   
  48.     @OnError  
  49.     public void onError(Session session, Throwable error) {  
  50.         error.printStackTrace();  
  51.     }  
  52.   
  53.     public void sendMessageTo(String message, String To) throws IOException {  
  54.         // session.getBasicRemote().sendText(message);  
  55.         //session.getAsyncRemote().sendText(message);  
  56.         for (WebSocket item : clients.values()) {  
  57.             if (item.username.equals(To) )  
  58.                 item.session.getAsyncRemote().sendText(message);  
  59.         }  
  60.     }  
  61.       
  62.     public void sendMessageAll(String message) throws IOException {  
  63.         for (WebSocket item : clients.values()) {  
  64.             item.session.getAsyncRemote().sendText(message);  
  65.         }  
  66.     }  
  67.       
  68.       
  69.   
  70.     public static synchronized int getOnlineCount() {  
  71.         return onlineCount;  
  72.     }  
  73.   
  74.     public static synchronized void addOnlineCount() {  
  75.         WebSocket.onlineCount++;  
  76.     }  
  77.   
  78.     public static synchronized void subOnlineCount() {  
  79.         WebSocket.onlineCount--;  
  80.     }  
  81.   
  82.     public static synchronized Map<String, WebSocket> getClients() {  
  83.         return clients;  
  84.     }  


js:

  1. var websocket = null;  
  2. var username = localStorage.getItem("name");  
  3.   
  4. //判斷當前瀏覽器是否支持WebSocket  
  5. if ('WebSocket' in window) {  
  6.     websocket = new WebSocket("ws://" + document.location.host + "/WebChat/websocket/" + username + "/"+ _img);  
  7. else {  
  8.     alert('當前瀏覽器 Not support websocket')  
  9. }  
  10.   
  11. //連接發生錯誤的回調方法  
  12. websocket.onerror = function() {  
  13.     setMessageInnerHTML("WebSocket連接發生錯誤");  
  14. };  
  15.   
  16. //連接成功建立的回調方法  
  17. websocket.onopen = function() {  
  18.     setMessageInnerHTML("WebSocket連接成功");  
  19. }  
  20.   
  21. //接收到消息的回調方法  
  22. websocket.onmessage = function(event) {  
  23.     setMessageInnerHTML(event.data);  
  24. }  
  25.   
  26. //連接關閉的回調方法  
  27. websocket.onclose = function() {  
  28.     setMessageInnerHTML("WebSocket連接關閉");  
  29. }  
  30.   
  31. //監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。  
  32. window.onbeforeunload = function() {  
  33.     closeWebSocket();  
  34. }  
  35.   
  36. //關閉WebSocket連接  
  37. function closeWebSocket() {  
  38.     websocket.close();  

不全,請等待
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章