栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

websocket实现直播间实时在线人数-组播消息

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

websocket实现直播间实时在线人数-组播消息

springboot引入websocket
@Configuration
public class WebSocketConfig {
	//将服务加载到IOC容器中
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }

}
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.yunzan.app.domain.vo.LiveRoomTopThreeUserVo;
import com.yunzan.app.domain.vo.LiveRoomTopThreeUserWrapperVo;
import com.yunzan.app.service.impl.JyGiftRecordServiceImpl;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/app/liveRoom/{roomId}/{userId}/{type}")
@Component
public class WebSocketLiveRoomOnlineServer {

    
    private static ConcurrentHashMap> userIdCollection = new ConcurrentHashMap<>();

    
    private static ConcurrentHashMap> liveRoomCollection = new ConcurrentHashMap<>();

    private String liveId;

    private String userId;

    private Session session;

    //是否主播加入 1-是 2-否
    private Integer type;

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam("roomId") String liveId, @PathParam("userId") String userId, @PathParam("type") Integer type) {

        this.session = session;
        this.userId = userId;
        this.liveId = liveId;
        this.type = type;

        //不同房间的在线用户加入该客户端服务
        CopyOnWriteArraySet roomMumberClient = liveRoomCollection.get(liveId);
        if (BeanUtil.isNotEmpty(roomMumberClient)) {
            roomMumberClient.add(this);
        } else {
            roomMumberClient = new CopyOnWriteArraySet<>();
            roomMumberClient.add(this);
            liveRoomCollection.put(liveId, roomMumberClient);
        }


        //观看人数增加
        addOnlineCount(liveId, userId, type);
        System.out.println(userId + "加入房间 " + liveId + "!当前人数为" + getOnlineCount(liveId));
        ConcurrentHashSet userIds = userIdCollection.get(liveId);
        System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" + userIds);

        try {
            publishMessage(session, liveId, userIds);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //关闭连接时调用
    @OnClose
    public void onClose() throws IOException {
        //关闭连接移除客户端连接对象,否则下次无法建立连接
        if (this.session != null) {
            this.session.close();
        }
        //移除退出直播间的客户端对象
        CopyOnWriteArraySet roomMembers = liveRoomCollection.get(this.liveId);
        roomMembers.remove(this);

        subOnlineCount(this.liveId, this.userId);
        ConcurrentHashSet userIds = userIdCollection.get(liveId);
        publishMessage(this.session, liveId, userIds);
        System.out.println(this.userId + "" + this.liveId + "断开webSocket连接!当前人数为" + getOnlineCount(this.liveId));
    }

    public static synchronized int getOnlineCount(String liveId) {
        ConcurrentHashSet uIds = userIdCollection.get(liveId);
        return uIds.size();
    }

    public static synchronized void addOnlineCount(String liveId, String userId, Integer type) {
        //记录每个直播间的在线用户id
        if (type == 2) {
            ConcurrentHashSet userIds = userIdCollection.get(liveId);
            if (BeanUtil.isNotEmpty(userIds)) {
                userIds.add(userId);
            } else {
                ConcurrentHashSet uId = new ConcurrentHashSet<>();
                uId.add(userId);
                userIdCollection.put(liveId, uId);
            }
        }
    }

    public static synchronized void subOnlineCount(String liveId, String userId) {
        //删除每个直播间的下线用户id
        ConcurrentHashSet userIds = userIdCollection.get(liveId);
        if (BeanUtil.isNotEmpty(userIds)) {
            userIds.remove(userId);
        }
    }

    
    public static ConcurrentHashSet getUserIdCollection(String liveId) {
        return userIdCollection.get(liveId);
    }

    //消息广播到对应客户端
    public void publishMessage(Session session, String liveId, ConcurrentHashSet userIds) throws IOException {

        //返回在线人数
        int onlineCount = getOnlineCount(liveId);
        StringBuffer onlineCountStr = null;
        if (onlineCount > 9999) {
            onlineCountStr = new StringBuffer(new BigDecimal(onlineCount).divide(new BigDecimal(10000), 1, BigDecimal.ROUND_DOWN).toString() + "w");
        } else {
            onlineCountStr = new StringBuffer(String.valueOf(onlineCount));
        }
        LiveRoomTopThreeUserWrapperVo threeUserWrapper = new LiveRoomTopThreeUserWrapperVo();
        threeUserWrapper.setOnlineNum(onlineCountStr.toString());

        //解决@Autowired无法注入问题
        JyGiftRecordServiceImpl jyGiftRecordService = SpringUtil.getBean(JyGiftRecordServiceImpl.class);

        List liveRoomTopThreeUserVos = jyGiftRecordService.queryRommTopThree(liveId, userIds);
        threeUserWrapper.setList(jyGiftRecordService.queryRommTopThree(liveId, userIds));

        String res = JSONObject.toJSONString(threeUserWrapper);

        //组播---每次操作liveId都会赋值给全局变量
        CopyOnWriteArraySet roomMembers = liveRoomCollection.get(this.liveId);
        for (WebSocketLiveRoomOnlineServer roomMember : roomMembers) {
            roomMember.sendMessage(res);
        }

        //广播
        
    }


    //给指定用户发送信息
    


    //收到客户端信息
    @OnMessage
    public void onMessage(String message) throws IOException {

    }

    //发送消息
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("发生错误");
        throwable.printStackTrace();
    }
}

简单统计在线人数
@ServerEndpoint("/app/online/{userId}")
@Component
public class WebSocketAppOnlineServer {

    // 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent 包的线程安全 Set ,用来存放每个客户端对应的 MyWebSocket 对象。
    private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet();

    // 与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    // 接收 userId
    private Long userId = null;

    // 创建一个数组用来存放所有需要向客户端发送消息的userId
    private static ConcurrentHashSet list = new ConcurrentHashSet();

    
    public static ConcurrentHashSet getList() {
        return list;
    }


    
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Long userId) {
        this.session = session;
        this.userId = userId;

        if (!list.contains(userId)) {
            list.add(userId);
            webSocketSet.add(this);  //加入set中
            addOnlineCount();   //在线数加1
            try {
                sendMessage("连接成功!");
                System.out.println("有新用户上线:" + userId + ",当前在线人数为:" + getOnlineCount());
            } catch (IOException e) {
                System.out.println("websocket IO Exception");
            }
        } else {
            try {
                list.add(userId);
                sendMessage("连接失败!该用户已连接了!");
                System.out.println("有一个重复的窗口开始监听:" + userId + " 未将它添加至客户端");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/930539.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号