代码之家  ›  专栏  ›  技术社区  ›  almog.ori

使这个httphandler更健壮?

  •  0
  • almog.ori  · 技术社区  · 15 年前

    我有以下httphandler;我使用它将更新推送到浏览器(在这里实现jquery和growlui),而不需要浏览器进行轮询。我认为我所完成的就是将轮询循环移到服务器上。

    有人能告诉我如何使这个类更健壮和可扩展吗?

    这是密码。

    public class LiveUpdates : IHttpHandler
    {
        //TODO: Replace this with a repository that the application can log to.
        private static readonly Dictionary<string, Queue<string>> updateQueue;
        static LiveUpdates()
        {
            updateQueue = new Dictionary<string, Queue<string>>();
        }
    
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Buffer = true;
    
            while (context.Response.IsClientConnected)
            {
                if (context.User == null) return;
                if (!context.User.Identity.IsAuthenticated) return;
    
                Thread.Sleep(1000);
                if (!updateQueue.ContainsKey(context.User.Identity.Name)) continue;
                if (updateQueue[context.User.Identity.Name].Count == 0) continue;
    
                GrowlStatus(context.Response, updateQueue[context.User.Identity.Name].Dequeue());
            }
    
    
        }
    
        protected static void GrowlStatus(HttpResponse Response, string Message)
        {
            // Write out the parent script callback.
            Response.Write(String.Format("<script type=\"text/javascript\">parent.$.growlUI('Message', '{0}');</script>", Message));
            // To be sure the response isn't buffered on the server.    
            Response.Flush();
        }
    
        public static void QueueUpdate(IPrincipal User, string UpdateMessage)
        {
            if (!updateQueue.ContainsKey(User.Identity.Name))
            {
                updateQueue.Add(User.Identity.Name, new Queue<string>());
            }
            updateQueue[User.Identity.Name].Enqueue(UpdateMessage);
        }
    
        public static void ClearUpdates(IPrincipal User)
        {
            if (updateQueue.ContainsKey(User.Identity.Name)) updateQueue.Remove(User.Identity.Name);
        }
    
    2 回复  |  直到 15 年前
        1
  •  2
  •   Rubens Farias    15 年前

    如果你打算使用 Thread.Sleep() ,必须实现 System.Web.IHttpAsyncHandler 否则处理程序将无法缩放。

        2
  •  1
  •   Doug T.    15 年前

    如何调用QueueUpdate?我注意到您从中获取字符串,并将其直接放到您要发送回用户的javascript中。用户是否有可能将javascript插入到条目中,并以某种方式让queueupdate显示出来?

    另外,在将消息放入您的javascript字符串之前,我会将它与有效的消息regex进行匹配。似乎有人可以很容易地完成您的growlui调用,然后插入自己的javascript。至少,您可以确保要插入的消息不包含单引号(“),它可以终止字符串并开始新的javascript命令。

    也许这只是偏执狂,但它会使它更强大。)