Websocket实现发送在线-离线消息

package com.cloudpan.common.websocket;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudpan.common.RedisCache;
import com.cloudpan.entity.pojo.SysUserMessage;
import com.cloudpan.service.SysUserMessageService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint("/im/{userId}")
@Component
@Slf4j
@Data
public class WebSocketIMServer {

    private static SysUserMessageService messageService;
    //用来存储在线用户的信息
    private static RedisCache redisCache;

    private static Integer onlineCount = 0;
    private static Map<String, Session> clients = new ConcurrentHashMap();
    private Session session;
    private String userId;

    @Autowired
    public void setSysUserMessageService(RedisCache redisCache){
        WebSocketIMServer.redisCache = redisCache;
    }

    @Autowired
    public void setRedisCache(SysUserMessageService messageService){
        WebSocketIMServer.messageService = messageService;
    }

    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) {
        this.userId = userId;
        this.session = session;
        WebSocketIMServer.onlineCount++;
        clients.put(userId, session);
        //用户上线 判断有无 离线消息 有 发送离线消息
        OffMsgSend(userId);

        log.info("【websocket消息】连接成功, 总数:{},{}", clients.size(),clients);
        //在redis中存储在线用户的key
        Set<String> onlines = clients.keySet();
        redisCache.setCacheSet("onlines",onlines);

        log.info("当前在线的用户为:{}",onlines);
    }

    //用户每次连接,判断是否存在离线消息,从数据库获取
    public void OffMsgSend(String key){
        LambdaQueryWrapper<SysUserMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserMessage::getToId,key)
                .eq(SysUserMessage::getOffMsg,"1");
        List<SysUserMessage> list = messageService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)){
            // 不为空 则 发送离线消息
            for (SysUserMessage sysUserMessage : list) {
                JSONObject object = JSON.parseObject(sysUserMessage.getTextMessage());
                String fromId = object.getString("fromId");
                String toId = object.getString("toId");
                String textMessage = object.getString("textMessage");
                sendUser(textMessage,toId);
            }
            list.forEach(ele -> {
                ele.setOffMsg("0");
            });
            //更新为不是离线消息
            messageService.updateBatchById(list);

        }

    }

    @OnClose
    public void onClose() {
        Session session = clients.get(userId);
        if (!ObjectUtils.isEmpty(session)){
            clients.remove(userId);
            WebSocketIMServer.onlineCount--;

            //更新redis中的在线人数信息
            redisCache.deleteObject("onlines");
            Set<String> newOnelines= clients.keySet();
            redisCache.setCacheSet("onlines",newOnelines);
            log.info("【websocket消息】连接断开, 总数:{}", clients.size());
        }

    }

    @OnMessage
    public void onMessage(String message) {
        log.info("【Websocket消息】收到客户端发来的消息:{}", message);
        //将前端传来的数据进行转型
        JSONObject object = JSON.parseObject(message);
        //获取所有数据
        String fromId = object.getString("fromId");
        String toId = object.getString("toId");
        //String textMessage = object.getString("textMessage");

        Session toUser = clients.get(toId);

        SysUserMessage sysUserMessage = new SysUserMessage();
        sysUserMessage.setFromId(fromId);
        sysUserMessage.setToId(toId);
        sysUserMessage.setTextMessage(message);
        if (toUser != null){
            sendUser(message,toId);
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
            messageService.save(sysUserMessage);

        }else {
            //不在线情况 需要给发送消息者发送一份
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
            sysUserMessage.setOffMsg("1");
            //离线消息
            messageService.save(sysUserMessage);
        }

    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
        log.error("WebSocket发生错误:" + throwable.getMessage());
    }

    //群发
    public void sendAllUser(String message) {
        // 向所有连接websocket的客户端发送消息
        for (Session item : clients.values()) {
            item.getAsyncRemote().sendText(message);
        }
        log.info("【发送消息】:", userId + "向" + clients.size() + "人发送消息:" + message);
    }

    //私发
    public void sendUser(String message,String toUserId) {
        //获取待发送的用户
        Session user = clients.get(toUserId);
        try {
            user.getBasicRemote().sendText(message);
            log.info(userId +  "消息发送拉,{}",message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值