標籤:
WebSocket,簡單理解就是H5內建的一套Socket API,用它來實現用戶端與服務端的長串連。
使用案例: 實現一個活動的即時報道,也就是圖文直播功能
MyWebSocket.java
這個就是socket的服務端,功能方面只需添加相應的註解即可,注意類名上的註解@ServerEndpoint(“/websocket”),這個/websocket就好比是配置在web.xml中的servlet url一樣。
H5用戶端對應這個服務端實現資訊的互動
package websocket.server;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;//該註解用來指定一個URI,用戶端可以通過這個URI來串連到WebSocket。類似Servlet的註解mapping。無需在web.xml中配置。@ServerEndpoint("/websocket")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為與某個用戶端的串連會話,需要通過它來給用戶端發送資料 * @throws IOException */ @OnOpen public void onOpen(Session session) throws IOException { this.session = session; webSocketSet.add(this); // 加入set中 addOnlineCount(); // 線上數加1 System.out.println("有新串連加入!當前線上人數為" + getOnlineCount()); //類比從資料庫中取出曆史資訊 this.sendMessage("<img src=‘http://localhost/websocket/image/water.gif‘>"); this.sendMessage("這是第一張現場圖,散水.gif"); this.sendMessage("<hr />"); this.sendMessage("<img src=‘http://localhost/websocket/image/test.jpg‘>"); this.sendMessage("這是第二張圖哦....."); this.sendMessage("<br/>"); this.sendMessage("---------------------------以上是曆史資訊---------------------------<br/>"); } /** * 串連關閉調用的方法 */ @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("<img src=‘http://localhost/websocket/image/water.gif‘>");//類比上傳的圖片 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--; }}
LiveServlet.java
這個是用來統一入口的,即使用者通過唯一路徑http://localhost/websocket進入直播
package websocket.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LiveServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub String method = req.getParameter("method"); if ("tolive".equals(method)) { req.getRequestDispatcher("/WEB-INF/jsp/client.jsp").forward(req, resp); }else if("fabu".equals(method)){ //這裡實現檔案上傳後返回圖片url給用戶端,用戶端發送這個url給websocket服務端,此處應有代碼...請腦補 } }}
服務端就這麼簡單的實現了下,具體根據自己的商務邏輯處理,再來看看用戶端
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";%><!DOCTYPE HTML><html><head><base href="<%=basePath%>"><title>Client webSocket</title><script type="text/javascript" src="http://file.iqilu.com/custom/new/public/js/jquery-1.8.1.min.js"></script><script> $(document).ready(function() { }); function load() { $(".content").hide(); }</script><style type="text/css">img { width: 100px; height: 100px}</style></head><body onload="load()"> <br /> <br /> <p class="tip" style="color: #fe1234">正在進入圖文直播...</p> <div class="content"> <div id="message"></div> <p>快來發布你的現場圖吧~</p> <br /> <br /> <form action="http://localhost/websocket/liveservlet?method=fabu" method="post"> <input type="file" value="請選擇圖片" /><button onclick="upLoadFile()">上傳圖片</button> <input id="comment" type="text" value="來段簡短描述吧" /><br /> </form> <button onclick="send()">發布</button> <button onclick="closeWebSocket()">退出直播</button> </div></body><script type="text/javascript"> var websocket = null; //判斷當前瀏覽器是否支援WebSocket if (‘WebSocket‘ in window) { websocket = new WebSocket("ws://localhost/websocket/websocket"); } else { alert(‘Not support websocket‘) } //串連發生錯誤的回調方法 websocket.onerror = function() { setMessageInnerHTML("error"); }; //串連成功建立的回調方法 websocket.onopen = function(event) { $(".content").show(); $(".tip").text("2016XXXX線上峰會直播"); } //接收到訊息的回調方法 websocket.onmessage = function(event) { 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(‘comment‘).value; websocket.send(message); }</script></html>
互動基本就是這個樣子了,案例清晰明了,代碼也簡單,可以快速對websocket上手
項目源碼下載 (要收一分積分哦,搞點積分提升下逼格[笑])
使用WebSocket實現圖文直播功能