JAVA使用WebSocket显示实时在线浏览人数

摘要:
˃˃scanned){//在这里会把含有@ServerEndpoint注解的类扫描加载进来,可以在这里做过滤等操作returnscanned;}}操作类ContentWebSocket.javapackagecom.websocket;importjavax.websocket.*;importjavax.websocket.server.ServerEndpoint;importjava.io.IOException;importjava.util.*;/***@author。*/@ServerEndpointpublicclassContentWebSocket{/***内容集合*/publicstaticMapcontentMap=newHashMap();/***创建*@paramsession*/@OnOpenpublicvoidonOpen{}/***发送消息*@paramcontentId*@throwsIOException*/@OnMessagepublicvoidsendMessage{Listc=contentMap.get;if{c=newArrayList();}c.add;//创建时把当前会话放在集合中,这样集合大小就是实时浏览人数contentMap.put;broadcast;}/***关闭*/@OnClosepublicvoidonClose{Map˂String,List˃requestParameterMap=session.getRequestParameterMap();//关闭时从链接获取content的IDListcontentids=requestParameterMap.get;if(contentids!

有时候我们需要在内容详情页实时浏览人数,这时候我们可以使用websocket实现这个功能

pom.xml

          <dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>8.0</version>
			<scope>provided</scope>
		</dependency>

或者jar包

tomcat7-websocket.jar

websocket-api.jar 

配置类

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>

免责声明:文章转载自《JAVA使用WebSocket显示实时在线浏览人数》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇delphi 去掉TreeView水平滚动条WCF:调用方未由服务器进行身份验证下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

Asp.Net开源服务端框架,WebApi后端框架(C#.NET)

本文主要介绍了基于Asp.Net平台、C#语言+SQL数据库的服务器的WebApi后端框架。K=WebApi&c=1&p=1.NETWebApi开发框架|MVC框架|后端框架|服务器框架-标准版本V1.0适用开发:快速构建支持多个客户端的服务器程序,并支持APP、B/S、c/S跨平台移动终端等。C/S系统开发框架的高级版本或更高版本支持多种后...

k8s集群上删除pod及service

删除k8s集群中的pod:找到pod的名称空间,并根据名称空间删除pod1。首先删除pod2,然后删除相应的部署。否则,删除pod是无用的。您还将看到pod,因为deployment.yaml文件中定义的副本数如下:delete the pod[root@test2~]#kubectlgetpod-njenkinsNAMEREADYSTATUSRESTART...

bootstrap删除模态框弹出并询问是否删除【通用删除模态框】

divclass=“模态对话框”&gt;divclass=“modal header”&gt;spanaria hidden=“true”&gt;h4class=“模态标题”&gt;divclass=“modal body”&gt;divclass=“模态页脚”&gt;...

PHP 垃圾回收机制(转)

GC进程通常从每个会话开始运行。GC的目的是在会话文件过期__destruct/unset__destruct()析构函数后自动销毁和删除它们。PHP将使用全局变量session.gc_Probability和session.gc_advisor的值session.gc_Probability=1,...

pycharm最新版本激活码(永久有效) python安装教程

输入python以查看当前版本的python。您可以输入“print'helloworld”并单击下载以启动PyCharm://pan.baidu.com//1eVdm4dUPKn3ZY_Xj kqNXw提取代码:l83f2,下载破解补丁(版本2018.3.5)下载链接至地址:...

Corn表达式

CronTriggerCronTrigger通常比SimpleTrigger更有用。如果您需要基于日历的概念,而不是SimpleTrigger完全指定的时间间隔,则重复启动工作的时间表。CronTrigger,您可以指定触发器计划,例如“每周五中午”、“每工作日9:30”,甚至“每周一上午、周三和周五9:00和10:00每五分钟”。即使如此,就像Simple...