利用websocket同账号登录WEB系统自动T除前一个登录者并且页面弹出消息提示

以下为websocket  js代码

var userId = $('#userId').val();
$(function () {
    if (userId != null && userId != '') {
        webSocketMsg();
    }
});
// 获取WebSocket推送的数据
function webSocketMsg() {
    //判断浏览器是否支持websocket
    if (window.WebSocket) {
        var websocket = new WebSocket(webSocketUrl + "/systemWebsocket?" + userId);
        websocket.onerror = function (event) {
            onError(event);
        };
        websocket.onopen = function (event) {
            onOpen(event);
        };
        websocket.onmessage = function (event) {
            console.log("收到消息啦:" + event.data);
            var objTemp = JSON.parse(event.data);
            var imType = objTemp.type;
            var obj = objTemp.messageObj;
            if ("KickOut" == imType) {
                bootbox.dialog({
                    message: "您的账号在另一台设备上登录,您被挤下线,请重新登录!",
                    buttons: {
                        "success": {
                            "label": "确定",
                            "className": "btn-primary",
                            "callback": function () {
                                window.location.href = ctx + '/logout';
                            }
                        }
                    }
                });
            }
        };
    }
}

// 设置消息数量
function setMsgCount(count) {
    //todo
}
function onOpen(event) {
    //todo
}
function onError(event) {
    //alert(event.data);
}
function start() {
    return false;
}
    




后台 代码 (ps:map简单,代码木有贴)


@ServerEndpoint(value = "/systemWebsocket", configurator = GetHttpSessionConfigurator.class)
public class ImSystemWebsocketController {
 // 与某个客户端的连接会话,需要通过它来给客户端发送数据
 private Session session;
 // 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
 private static int onlineCount = 0;
 private HttpSession httpSession;
 @OnOpen
 public void onOpen(Session session, EndpointConfig config) {
  String userId = session.getQueryString();
  this.session = session;
  this.httpSession = (HttpSession) config.getUserProperties().get(
    HttpSession.class.getName());
  String httpSessionId = httpSession.getId();
  if (DdMessageUtils.httpSessionWebSocketMap.containsKey(httpSessionId)) { // 缓存有浏览器httpsession,则增加页面数websockeseesion
   boolean flag = true;
   ArrayList listSession = DdMessageUtils.httpSessionWebSocketMap
     .get(httpSessionId);
   for (Session item : listSession) {
    if (item.getId().equals(session.getId())) {
     flag = false;
    }
   }
   if (flag) {
    listSession.add(session);
   }
  } else {// 缓存没有,增加httpSessionWebSocketMap和httpSessionUserIdMap
   ArrayList listSession = new ArrayList();
   if (DdMessageUtils.httpSessionUserIdMap.containsKey(userId)) {
    // 这个用户存在,但是httpSessionId不一样,需要发消息,踢除原来页面
    JSONObject toMessage = new JSONObject();
    toMessage.put("kickOut", "该用户已在其他地方登录,请重新登录!");
    WebMessage webMessage = new WebMessage();
    webMessage.setType(MessageType.KickOut);
    webMessage.setMessageObj(toMessage);
    for (Session item : DdMessageUtils.httpSessionWebSocketMap
      .get(DdMessageUtils.httpSessionUserIdMap.get(userId))) {
     item.getAsyncRemote().sendText(
       DdJsonUtils.toJSONString(webMessage));// 即时发送消息
    }
    DdMessageUtils.httpSessionWebSocketMap
      .remove(DdMessageUtils.httpSessionUserIdMap.get(userId));
    DdMessageUtils.httpSessionUserIdMap.remove(userId);// 清楚原来缓存
    DdMessageUtils.sessionMap.remove(userId); // IM聊天的缓存也要清除掉
    listSession.add(this.session);
    DdMessageUtils.httpSessionWebSocketMap.put(httpSessionId,
      listSession);
    DdMessageUtils.httpSessionUserIdMap.put(userId, httpSessionId);
   } else {
    listSession.add(session);
    DdMessageUtils.httpSessionWebSocketMap.put(httpSessionId,
      listSession);
    DdMessageUtils.httpSessionUserIdMap.put(userId, httpSessionId);
    this.addOnlineCount();
    System.out.println("有新连接加入!当前在线人数为" + this.getOnlineCount());
   }
  }
 }
 /**
  * 连接关闭调用的方法
  */
 @OnClose
 public void onClose() {
  String userId = session.getQueryString();
  if (DdMessageUtils.httpSessionWebSocketMap.get(
    DdMessageUtils.httpSessionUserIdMap.get(userId)).contains(
    this.session)) {
   DdMessageUtils.httpSessionWebSocketMap.get(
     DdMessageUtils.httpSessionUserIdMap.get(userId)).remove(
     this.session);
  }
  if (DdMessageUtils.httpSessionWebSocketMap.get(
    DdMessageUtils.httpSessionUserIdMap.get(userId)).size() < 1) {
   this.subOnlineCount();
   System.out.println("有一连接关闭!当前在线人数为" + this.getOnlineCount());
  }
 }
 @OnMessage
 public void onMessage(final String message, Session session) {
  System.out.println("来自客户端的消息:" + message);
 }
 /**
  * 发生错误时调用
  *
  * @param session
  * @param error
  */
 @OnError
 public void onError(Session session, Throwable error) {
  System.out.println("发生错误");
  error.printStackTrace();
 }
 public synchronized int getOnlineCount() {
  return onlineCount;
 }
 public synchronized void addOnlineCount() {
  ImSystemWebsocketController.onlineCount++;
 }
 public synchronized void subOnlineCount() {
  ImSystemWebsocketController.onlineCount--;
 }

你可能感兴趣的:(利用websocket同账号登录WEB系统自动T除前一个登录者并且页面弹出消息提示)