JAVA使用WebSocket显示实时在线浏览人数
有时候我们需要在内容详情页实时浏览人数,这时候我们可以使用websocket实现这个功能
pom.xml
1 2 3 4 5 6 | < 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | < 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
-----------------------有任何问题可以在评论区评论,也可以私信我,我看到的话会进行回复,欢迎大家指教------------------------
(蓝奏云官网有些地址失效了,需要把请求地址lanzous改成lanzoux才可以)
分类:
JAVA
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了