JAVA----websocket,一对一, 在线人数

一对一, 在线人数

可以在线人员发送信息,扩展:可强退在线人员

@Slf4j
@ServerEndpoint(value = "/websocket/online/{userId}", configurator = SpringWebSocketConfig.class)
@Component
public class OnlineUserWebSocket {

    private static AtomicInteger onlineCount = new AtomicInteger(0);  // 记录当前在线连接数
    private static Map<String, Session> clients = new ConcurrentHashMap<>();    // 存放所有在线的客户端
    private static int timeout = 8*3600;
    private Session session;
    private String userId = "";
    private Integer roleId = 0;

    public String getUserKey() {
        return CacheConstant.ONLINE_USER + userId;
    }

    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session, EndpointConfig config) throws Exception {
        if (!ConfigServiceUtils.getOnOrOff(ConfigConstant.SYS_ONLINE_USER_WEBSOCKET_OR_NOT)) {
            log.error("系统未开启在线用户 WebSocket");
            onClose(session);
            return;
        }

        this.userId = userId;
        this.session = session;
        Object obj = JSONObject.parseObject(JsonUtils.mapper(session.getUserPrincipal())).get("object");
        UserPrincipal userPrincipal = JSON.toJavaObject((JSON) obj, UserPrincipal.class);

        if (Objects.isNull(userPrincipal) || StringUtils.isEmpty(userId)) {
            sendMessage("Fail...onOpen", session);
            onClose(session);
            return;
        }
        this.roleId = userPrincipal.getRoleId();

        if (clients.containsKey(userId)) {
            CacheUtils.delete(getUserKey());
            clients.remove(userId);
        } else {
            onlineCount.incrementAndGet();
        }
        CacheUtils.set(getUserKey(), obj, timeout);
        clients.put(userId, session);

        log.info("用户:{}, ID: {}, 连接打开,当前在线人数为:{}", userPrincipal.getUsername(), userId, onlineCount.get());
        sendMessage("Connect success...", session, true);
    }

    @OnClose
    public void onClose(Session session) {
        log.info("用户ID: {},连接关闭,当前在线人数为:{}", userId, onlineCount.get());
        if (clients.containsKey(userId)) {
            clients.remove(userId);
            CacheUtils.delete(getUserKey());
            onlineCount.decrementAndGet();
        }
    }

    @OnMessage
    public void OnMessage(String message, Session session) {
        log.info("收到客户端[{}]的信息:{}", userId, message);
        try {
            WebSocketMessage webSocketMessage = JSON.parseObject(message, WebSocketMessage.class);
            log.info(webSocketMessage.toString());

            if (webSocketMessage != null) {
                Session toSession = clients.get(webSocketMessage.getUserId());
                if (toSession != null) {
                    this.sendMessage(webSocketMessage.getMessage(), toSession);
                } else {
                    log.info("发送信息失败,没有找到配置的用户:{}", webSocketMessage.getUserId());
                }
            }
        } catch (Exception e) {
            log.error("解析失败:{}", e);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("SessionID:" + session.getId() + ",Message:" + error.getMessage());
    }


    private void sendMessage(String message, Session toSession) {
        sendMessage(message, toSession, false);
    }

    private void sendMessage(String message, Session toSession, boolean always) {
        try {
            AjaxResult result = new AjaxResult();
            result.put(result.CODE_TAG, this.code);
            result.put(result.MSG_TAG, message);

            log.info("服务器给客户端, 发送者:{},拉收者:{}", session.getId(), toSession.getId());
            if (always || !session.getId().equals(toSession.getId())) {
                toSession.getBasicRemote().sendText(JSON.toJSONString(result));
            }

        } catch (Exception e) {
            log.error("服务器发送信息给客户端失败:{}", e);
        }
    }

}
实体
@Data
public class WebSocketMessage {

    public String userId;
    public String message;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值