SignalR - 如果集线器在线,则显示消息

时间:2014-11-04 11:40:32

标签: javascript jquery signalr

我正在建立聊天,客户可以与支持团队聊天。

所有客户网站都有聊天记录。支持团队有一个站点。当支持团队登录到该站点时。集线器连接可用,聊天打开。

但是在客户端网站上,如何在supportTeam启动集线器时显示消息:如下所示:

alert('cht is now online');

我的尝试:

ChatHub.cs

public void AdminJoin()
    {
        var adminUser = "Chat is now open"

        Clients.All.AdminIsOnline(adminUser);
    }

客户网站上的代码:

chat.on('AdminIsOnline', function (adminUser) {
            adminHasJoined(adminUser);
        });

        function adminHasJoined(adminUser) {
            alert(adminUser);
        };

以上代码仅在刷新客户端网站页面时以及SuppertTeam网站在线时运行。 我希望每次suppoertTeam登录时都会显示警报。不仅仅是在pageRefresh

1 个答案:

答案 0 :(得分:0)

简而言之: 1.继承OnConnect方法。 2.将用户添加到组。 3.创建方法,该方法将通知组的所有成员有关新组成员的信息。 4.使用JS通知客户端的事件。 Hub示例:

public class ChatHub : Hub
    {

        PREPP2Entities db = new PREPP2Entities();
        //Send message to chat room
        public void SendChatMessage(string gn, string name, string message)
        {
            Clients.Group(gn).addChatMessage(name, message);
            UserStatus();
        }
        //Public method that available on client side and used to update user status on user actions (e.g.Connect, disconnect
        public void UserStatus()
        {
            Clients.All.updateStatus();
        }
        public override Task OnConnected()
        {
            //get user data
            var x = (from a in db.Users where a.Login.Contains(Context.User.Identity.Name) select a.Role).FirstOrDefault();
            //Add to the list of online users
            if (AlreadyOnline(Context.ConnectionId) == false)
            {
                try
                {
                    UsersOnline uo = new UsersOnline();
                    uo.ConnectionID = Context.ConnectionId;
                    uo.UserName = Context.User.Identity.Name;
                    uo.UserRole = x;
                    uo.Created = DateTime.Now;
                    db.UsersOnline.Add(uo);
                    db.SaveChanges();
                }
                catch (DbEntityValidationException ex)
                {
                    var errorMessages = ex.EntityValidationErrors
                            .SelectMany(y => y.ValidationErrors)
                            .Select(y => y.ErrorMessage);
                    var fullErrorMessage = string.Join("; ", errorMessages);
                    var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
                    throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
                }
                //User with role "User"
                if (x == 1)
                {
                    //Add user to group
                    JoinGroup(Context.ConnectionId, Context.User.Identity.Name, true);
                    var operatorName = GetOperator();
                    //Find connection id
                    var cid = (from a in db.UsersOnline where a.UserName.Contains(operatorName) & a.UserRole == 2 select a.ConnectionID).FirstOrDefault();
                    if (cid != null & !String.IsNullOrEmpty(cid))
                    {
                        //Add user to group
                        JoinGroup(cid, Context.User.Identity.Name, false);
                    }
                    else
                    {
                        //Message that nobody's here
                        StringBuilder sb = new StringBuilder(200);
                        sb.AppendFormat("Здравствуйте {0}! ", Context.User.Identity.Name);
                        sb.Append("К сожалению сейчас наших стилистов нет в сети.<br />");
                        sb.Append("Вы можете оставить сообщение, которое будет прочитано позже.");
                        string message = sb.ToString();
                        SendChatMessage(Context.User.Identity.Name, "PREPP", message);
                    }
                }
                //Else user role belong to support team
                else
                {
                    //Find users that has this support team to talk
                    var oid = (from a in db.Users where a.Login.Contains(Context.User.Identity.Name) select a.Id).FirstOrDefault();
                    var u = (from a in db.UsersOnline
                             join b in db.Users on a.UserName equals b.Login
                             where a.UserRole == 1 & b.OperatorID == oid
                             select a.UserName).ToArray();
                    foreach (string n in u)
                    {
                        JoinGroup(Context.ConnectionId, n, false);
                    }
                }
            }
            UserStatus();
            return base.OnConnected();
        }
        public void JoinGroup(string connectionid, string groupName, bool send)
        {
            try
            {
                GroupInfo gi = new GroupInfo();
                gi.UserConnection = connectionid;
                gi.GroupName = groupName;
                gi.Created = DateTime.Now;
                db.GroupInfo.Add(gi);
                db.SaveChanges();
                Groups.Add(connectionid, groupName);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);
                var fullErrorMessage = string.Join("; ", errorMessages);
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
                throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
            }
            if (send == true)
            {
                var on = GetOperator();
                StringBuilder sb = new StringBuilder(200);
                sb.AppendFormat("Здравствуйте {0}! ", Context.User.Identity.Name);
                sb.AppendFormat("Я Ваш личный стилист - {0}. ", on);
                sb.Append("Чем сегодня я могу помочь Вам?");
                string message = sb.ToString();
                SendChatMessage(groupName, on, message);
            }
            UserStatus();
        }
        public bool AlreadyOnline(string connectionid)
        {
            bool exist;
            var x = db.UsersOnline.Where(p => p.ConnectionID.Contains(connectionid)).Count();
            if (x > 0)
            {
                exist = true;
            }
            else
            {
                exist = false;
            }
            return exist;
        }
        public override Task OnDisconnected()
        {
            StringBuilder sb = new StringBuilder(100);
            sb.AppendFormat("Пользователь {0} не в сети!", Context.User.Identity.Name);
            string message = sb.ToString();
            SendChatMessage(Context.User.Identity.Name, "PREPP", message);
            UserStatus();
            db.GroupInfo.RemoveRange(db.GroupInfo.Where(x => x.UserConnection.Contains(Context.ConnectionId)));
            db.UsersOnline.RemoveRange(db.UsersOnline.Where(x => x.UserName.Contains(Context.User.Identity.Name)));
            db.SaveChangesAsync();
            UserStatus();
            return base.OnDisconnected();
        }
        public override Task OnReconnected()
        {
            StringBuilder sb = new StringBuilder(100);
            sb.AppendFormat("Пользователь {0} вернулся к нам!", Context.User.Identity.Name);
            string message = sb.ToString();
            SendChatMessage(Context.User.Identity.Name, "PREPP", message);
            UserStatus();
            return base.OnReconnected();
        }
        public string GetOperator()
        {
            //Возвращаем имя оператора если он был назначен ранее
            var oid = (from a in db.Users where a.Login.Contains(Context.User.Identity.Name) select a.OperatorID).FirstOrDefault();
            if (oid.HasValue)
            {
                return db.Users.Where(x => x.Id == oid).Select(x => x.Login).SingleOrDefault();
            }
            //Выбираем и добавляем пользователю случайного оператора
            else
            {
                //выбираем всех пользователей с ролью оператора
                var opname = (from a in db.UsersOnline where a.UserRole == 2 orderby (Guid.NewGuid()) select a.UserName).FirstOrDefault();
                //Назначем пользователю оператора
                var opid = (from a in db.Users where a.Login.Contains(opname) select a.Id).SingleOrDefault();
                if (opid > 0)
                {
                    WriteOperator(Context.User.Identity.Name, opid);
                    return opname;
                }
                else
                {
                    var op = (from a in db.Users where a.Role == 2 orderby (Guid.NewGuid()) select a.Id).FirstOrDefault();
                    WriteOperator(Context.User.Identity.Name, op);
                    return db.Users.Where(x => x.Id == op).Select(x => x.Login).SingleOrDefault();
                }
            }
        }
         void WriteOperator(string username, int operatorid)
        {
            var uid = db.Users.Where(p => p.Login == username).Select(x => x.Id).FirstOrDefault();
            var a = db.Users.Find(uid);
            if (a != null)
            {
                a.OperatorID = operatorid;
                db.SaveChanges();
            }
            else throw new Exception();

}     }