使这个HttpHandler的更稳健?
-
22-09-2019 - |
题
我有以下的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);
}
解决方案
如果您打算使用Thread.Sleep()
,必须实现系统.Web.IHttpAsyncHandler 或处理程序不能扩展。
其他提示
如何QueueUpdate叫什么名字?我注意到您从采取串并直接将其放入您发送回用户的JavaScript。是否有一个用户可以插入JavaScript的条目,并有QueueUpdate莫名其妙地显示它后面的任何机会呢?
另外,我想对一个有效的消息正则表达式把它变成你的JavaScript字符串匹配之前的消息。这似乎是一个人能完成你的growlUi呼叫,然后很容易地插入自己的JavaScript。至少,你可以确保你将不包含一个单引号(')可能终止字符串,并开始一个新的JavaScript命令的消息。
也许这只是妄想,但会使其更加坚固:)
不隶属于 StackOverflow