有時候我們需要在內容詳情頁實時瀏覽人數,這時候我們可以使用websocket實現這個功能
pom.xml
<dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>8.0</version> <scope>provided</scope> </dependency>
或者jar包
javax.websocket-api-1.0.jar
下載地址:https://yvioo.lanzous.com/i3AXkhl3s3c
配置類
WebSocketConfig.java
package com.config; import javax.websocket.Endpoint; import javax.websocket.server.ServerApplicationConfig; import javax.websocket.server.ServerEndpointConfig; import java.util.Set; public class WebSocketConfig implements ServerApplicationConfig { @Override public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> endpointClasses) { return null; } @Override public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) { //在這里會把含有@ServerEndpoint注解的類掃描加載進來 ,可以在這里做過濾等操作 return scanned; } }
操作類
ContentWebSocket.java
package com.websocket; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.*; /** * @author 。 */ @ServerEndpoint(value = "/content_websocket") public class ContentWebSocket { /** * 內容集合 */ public static Map contentMap=new HashMap<>(); /** * 創建 * @param session */ @OnOpen public void onOpen(Session session) { } /** * 發送消息 * @param contentId * @throws IOException */ @OnMessage public void sendMessage(Session session,String contentId) { List c = (List) contentMap.get(contentId); if (c==null){ c=new ArrayList(); } c.add(session); //創建時把當前會話放在集合中,這樣集合大小就是實時瀏覽人數 contentMap.put(contentId,c); broadcast(c,c.size()+""); } /** * 關閉 */ @OnClose public void onClose(Session session) { Map<String, List<String>> requestParameterMap = session.getRequestParameterMap(); //關閉時從鏈接獲取content的ID List<String> contentids = requestParameterMap.get("content_id"); if (contentids!=null&&contentids.size()>0){ String contentId=contentids.get(0); List c = (List) contentMap.get(contentId); if (c!=null){ //從集合中移除該會話 c.remove(session); contentMap.put(contentId,c); broadcast(c,c.size()+""); } } } /** * 發生錯誤 * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { System.out.println("發生錯誤"); error.printStackTrace(); } /** * 消息廣播 * @param sessions * @param msg */ public void broadcast(List<Session> sessions,String msg){ for (Iterator it=sessions.iterator();it.hasNext();){ Session session= (Session) it.next(); try { if (session.isOpen()){ //當當前會話沒有被關閉 發送消息 session.getBasicRemote().sendText(msg); }else { it.remove(); } } catch (IOException e) { e.printStackTrace(); it.remove(); } } } }
頁面代碼
content.html
<span id="viewing">0</span>人正在看 <script> //觀看人數統計 var ws; var target="ws:localhost:8080/content_websocket?content_id=內容ID"; $(function () { //處理瀏覽器兼容性 if ('WebSocket' in window) { ws = new WebSocket(target); } else if ('MozWebSocket' in window) { ws = new MozWebSocket(target); } else { alert('WebSocket is not supported by this browser.'); return; } ws.onopen = function () { ws.send('${content.id}') }; ws.onmessage = function (event) { $("#viewing").html(event.data); }; ws.onclose=function (event) { } }) </script>
https://yvioo.lanzous.com/i3AXkhl3s3c