微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Silverlight中用户直接退出浏览器时如何判断用户离线

最近在修改项目中遇到了当用户直接关闭浏览器时无法判断用户离线的难题,在网上找了一天的相关资料,网上提供的方法可总结为两种:

  • 心跳包,每间隔一段时间就传递一个当前时间,然后拿最后一个传过来的值跟当前的时间相比,如果超过了设定的值就判定该用户为离线;

  • 在App.xaml.cs中的Exit事件中调用JS的方法,在JS方法中再去调用WCF中的方法

第二种不明白具体该如何实现,清楚的可以留言相告一下啊!感激!!!!!

本人使用了第一种实现了,下面来具体说说:

  1. 首先在用户的类里添加一个UserLastTime字段用来表示用户最后的活动时间并赋初值为当前时间;

  2. 然后在服务端添加一个用于记录已经登录了的用户的列表List<UserData>;

  3. 带判断用户登录成功的地方把当前登录用户添加到List<UserData>中;

  4. 在主页面中使用dispatcherTimer 制作一个定时器来定时更新List<UserData>中当前用户的UserLastTime字段;

  5. 在需要判断用户是否已经离线的页面同样制作一个定时器来定时比较List<UserData>中当前用户的UserLastTime字段的值与当前系统时间的值,如果两值的差值超过一定的时间即可调用用法把当前用户从List<UserData>中移除。

下面来看一下具体代码

首先是添加用户到List<UserData>中并得到整个列表:

OnlineUserList.Add(CurrentUser);//用户登录成功后添加
public List<UserData> GetonlineUsers()//写一个方法用于返回已经登录了的所有用户
      {
         return OnlineUserList;
      }

其次是在页面中定时更新UserLastTime字段的值:

dispatcherTimer Timer = new dispatcherTimer();
Timer.Interval = new TimeSpan(5000);
Timer.Tick += new EventHandler(Timer_Tick);
Timer.Start();
void Timer_Tick(object sender,EventArgs e)
      {
            IProxy mproxy = Factory.Service;
            mproxy.SetUserLastTime(CurrentUser,result =>
            {

            });      
      } 
public string SetUserLastTime(UserData ud)
      {
         if (ud != null)
         {
            for (int i = 0; i < OnlineUserList.Count; i++)
            {
               if (OnlineUserList[i].Id == ud.Id)
               {
                  OnlineUserList[i].UserLastTime=DateTime.Now;
               }
            }
         }
         return "";
      }

最后是如果UserLastTime字段的值跟当前系统时间相差二十秒的话就将当前用户从List<UserData>中移除:

void Current_Exit(object sender,EventArgs e)
      {         <pre name="code" class="csharp">        IProxy mproxy = Factory.Service;
mproxy.OfflineUser(CurrentUser,result => { });
      }
public string OfflineUser(UserData ud) { if (ud != null) { for (int i = 0; i < OnlineUserList.Count; i++) { if (OnlineUserList[i].Id== ud.Id) { OnlineUserList.Remove(OnlineUserList[i]); } } } return ""; }
dispatcherTimer timer = new dispatcherTimer();
timer.Interval = new TimeSpan(3000);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
void timer_Tick(object sender,EventArgs e)
      {
       foreach (UserData ud in OnlineUsers)
       {
         DateTime cn = new DateTime();
         cn = DateTime.Now;
         if (ud.UserLastTime.AddSeconds(20) < cn)
            {
              UserData ud1 = new UserData();
              ud1.Id = ud.Id;
              ud1.Name = ou.Name;
              IProxy _proxy = Factory.Service;
              _proxy.OfflineUser(ud1,result => { });
             }
         }
<pre name="code" class="csharp"><pre name="code" class="csharp">       }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐