Tomcat方式實現WebSockethtml
Oracle官方規範定義了一組用於開發web socket應用的Java API,請參見:java
http://www.oracle.com/technetwork/articles/java/jsr356-1937161.htmlweb
用到的包以下:編程
javax.websocket.server包含註解,類,接口用於建立和配置服務端點 javax.websocket包含服務端和客戶端公用的註解,類,接口,異常
主類有兩種建立的方式:瀏覽器
Interface-Driven Approach 編程式的實現,須要繼承Endpoint類,重寫它的方法
public class myOwnEndpoint extends javax.websocket.Endpoint { public void onOpen(Session session, EndpointConfig config) {...} public void onClose(Session session, CloseReason closeReason) {...} public void onError (Session session, Throwable throwable) {...} } ``` Annotation-Driven Approach 註解式的實現,將本身的寫的類以及類中的一些方法用前面提到的包中的註解裝飾(@EndPoint,@OnOpen等等)
@ServerEndpoint("/websocket") public class WebSocketTest { @OnOpen public void start(Session session){ System.out.println("鏈接成功! " + session.getId()); }安全
@OnMessage public void reMessage(Session session, String str){ try { session.getBasicRemote().sendText(str + " who are you"); }catch (IOException e){ e.printStackTrace(); } } @OnError public void error(Session session, Throwable t){ t.printStackTrace(); } @OnClose public void close(){ }
當建立好一個(服務)端點以後,將它以一個指定的URI發佈到應用當中,這樣遠程客戶端就能鏈接上它了。 Websocket(服務)端點以URI表述,有以下的訪問方式:
ws://host:port/path?query wss://host:port/path?query服務器
實例代碼以下 JAVA類:
package me.gacl.websocket;websocket
import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet;session
import javax.servlet.http.HttpSession; 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;oracle
/**
@ServerEndpoint("/websocket")
public class WebSocketTest { //靜態變量,用來記錄當前在線鏈接數。應該把它設計成線程安全的。 private static int onlineCount = 0;
//concurrent包的線程安全Set,用來存放每一個客戶端對應的MyWebSocket對象。若要實現服務端與單一客戶端通訊的話,能夠使用Map來存放,其中Key能夠爲用戶標識 private static CopyOnWriteArraySet<WebSocketTest> webSocketSet = new CopyOnWriteArraySet<WebSocketTest>(); //與某個客戶端的鏈接會話,須要經過它來給客戶端發送數據 private Session session; //用來存放 httpSessionId/session 的map ,key 爲httpSessionId ,value 爲各個終端的session 對象 private static ConcurrentHashMap<String,WebSocketTest> httpSessionWebSocketMap = new ConcurrentHashMap<String,WebSocketTest>(); /** * 鏈接創建成功調用的方法 * @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(WebSocketTest 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{ if(this.session.isOpen()){ this.session.getBasicRemote().sendText(message); //this.session.getAsyncRemote().sendText(message); this.session.setMaxTextMessageBufferSize(102400); } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocketTest.onlineCount++; } public static synchronized void subOnlineCount() { WebSocketTest.onlineCount--; }
}
Web頁面: var websocket = null; //判斷當前瀏覽器是否支持WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://localhost:8080/JavaWebSocket/websocket"); } else { alert('當前瀏覽器 Not support websocket') } //鏈接發生錯誤的回調方法 websocket.onerror = function () { setMessageInnerHTML("WebSocket鏈接發生錯誤"); }; //鏈接成功創建的回調方法 websocket.onopen = function () { setMessageInnerHTML("WebSocket鏈接成功"); } //接收到消息的回調方法 websocket.onmessage = function (event) { setMessageInnerHTML(event.data); } //鏈接關閉的回調方法 websocket.onclose = function () { setMessageInnerHTML("WebSocket鏈接關閉"); } //監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket鏈接,防止鏈接還沒斷開就關閉窗口,server端會拋異常。 window.onbeforeunload = function () { closeWebSocket(); } //將消息顯示在網頁上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //關閉WebSocket鏈接 function closeWebSocket() { websocket.close(); } //發送消息 function send() { var message = document.getElementById('text').value; websocket.send(message); } 若是須要WebSocketSession和HttpSession通訊,則須要繼承ServerEndpointConfig.Configurator 類並重寫一些方法,來完成custom endpoint configuration 的邏輯代碼。 修改WebSocketTest.java:
@ServerEndpoint(value="/websocket",configurator=GetHttpSessionConfigurator.class) public class WebSocketTest{ private Session session; private HttpSession httpSession; }
custom endpoint configuration GetHttpSessionConfigurator的代碼
/** * */ import javax.servlet.http.HttpSession; import javax.websocket.HandshakeResponse; import javax.websocket.server.HandshakeRequest; import javax.websocket.server.ServerEndpointConfig; import javax.websocket.server.ServerEndpointConfig.Configurator;
/**
/ public class GetHttpSessionConfigurator extends Configurator { /* * */ public GetHttpSessionConfigurator() { // TODO Auto-generated constructor stub }
@Override public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { HttpSession httpSession = (HttpSession)request.getHttpSession(); config.getUserProperties().put(HttpSession.class.getName(),httpSession); }
}
運行結果以下: ![輸入圖片說明](https://static.oschina.net/uploads/img/201704/17182503_rQKG.png "在這裏輸入圖片標題")