0

我有以下 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);
    }
4

2 回答 2

2

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

于 2009-10-19T14:08:15.473 回答
1

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

此外,我会将 Message 与有效的消息正则表达式进行匹配,然后再将其放入您的 javascript 字符串中。似乎有人可以完成您的 growlUi 调用,然后很容易地插入他们自己的 javascript。至少您可以确保您插入的消息不包含单引号 ('),这可能会终止字符串并开始新的 javascript 命令。

也许这只是偏执狂,但它会使它更加健壮:)

于 2009-10-19T14:06:41.437 回答