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 {

    /**
     * 存储每个直播间在线的用户id
     * 直播间id,用户id
     */
    private static ConcurrentHashMap<String, ConcurrentHashSet<String>> userIdCollection = new ConcurrentHashMap<>();

    /**
     * 存储不同直播间中的客户端----给不同的直播间推送当前直播间的消息
     */
    private static ConcurrentHashMap<String, CopyOnWriteArraySet<WebSocketLiveRoomOnlineServer>> 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<WebSocketLiveRoomOnlineServer> 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<String> 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<WebSocketLiveRoomOnlineServer> roomMembers = liveRoomCollection.get(this.liveId);
        roomMembers.remove(this);

        subOnlineCount(this.liveId, this.userId);
        ConcurrentHashSet<String> 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<String> uIds = userIdCollection.get(liveId);
        return uIds.size();
    }

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

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

    /**
     * 直播间在线用户id-供controller调用进行DB操作
     * @param liveId
     * @return
     */
    public static ConcurrentHashSet<String> getUserIdCollection(String liveId) {
        return userIdCollection.get(liveId);
    }

    //消息广播到对应客户端
    public void publishMessage(Session session, String liveId, ConcurrentHashSet<String> 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<LiveRoomTopThreeUserVo> liveRoomTopThreeUserVos = jyGiftRecordService.queryRommTopThree(liveId, userIds);
        threeUserWrapper.setList(jyGiftRecordService.queryRommTopThree(liveId, userIds));

        String res = JSONObject.toJSONString(threeUserWrapper);

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

        //广播
        /*for (WebSocketLiveRoomOnlineServer server : webSocketSet) {
            server.sendMessage(res);
        }*/
    }


    //给指定用户发送信息
    /*public void sendInfo(String liveId, String userId, String message) {
        WebSocketLiveRoomOnlineServer socketController = sessionPools.get(userId + "" + liveId);
        try {
            sendMessage(socketController.session, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/


    //收到客户端信息
    @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();
    }
}

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

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

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

    // 接收 userId
    private Long userId = null;

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

    /**
     * 获得在线的用户id--供调用
     *
     * @return
     */
    public static ConcurrentHashSet<Long> 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();
            }
        }

    }

}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值