这两天在使用Asp.net MVC 4开发COMET消息通知机制,在后端使用异步线程对消息进行订阅,客户端通过AJAX长连接请求MVC中的ACTION,如:http://localhost/event/imageSet,即表示获取ImageSet对象的变更消息(新增,更新和删除消息)。
public interface IEntityEventTEntity>
{
//变更的实体类对象
TEntity[] Entities
{
get;
}
//操作类型
EntityEventType Type
{
get;
}
}
public enum EntityEventType : int
{
Create = 0,
Update = 1,
Removed = 2
}
[SessionState(SessionStateBehavior.ReadOnly)]
public class EntityEventController : Controller
{
//异步获取对ImageSet对象操作的变更事件Action,millsecondsTimeout为超时时间。
public async TaskActionResult> ImageSet(int millisecondsTimeout = 10000)
{
return await this.EventAsyncImageSetData>(millisecondsTimeout);
}
private async TaskActionResult> EventAsyncTEntity>(int millisecondsTimeout)
{
IEntityEventTEntity> entityEvent = await EntityEventSubcriber.Instance.WaitForEntityEventTEntity>(millisecondsTimeout);
return this.Json(new
{
HasEvent = null != entityEvent,
EntityEvent = entityEvent
}, JsonRequestBehavior.AllowGet);
}
}
(2) 如果Controller层面应用或者Filter中操作过Session,那么为了避免长链接时不会导至同一Session在其他调用中Session Block的情况,需要在Controller头上加入[SessionState(SessionStateBehavior.ReadOnly)] 的Attribute,来表示当前Controller对Session为只读操作,这样就其他操作就不会被阻塞了。
$(document).ready(function () {
var $hoverList = $("#imageSets").hoverList({title:"图片集列表", selectedIndex: 1 });
var getEvent = function(){
var getPattern = "/EasyshirtBackend/imageSet/0";
$.getJSON("/EasyshirtBackend/event/imageSet/100000" , function(data){
if(data.HasEvent){
//Create
if(data.EntityEvent.Type == 0){
$.each(data.EntityEvent.Entities, function(i, entity){
//TODO: 处理实体类新增
if(i == data.EntityEvent.Entities.length - 1){
getEvent();
}
});
return;
}
//Update
if(data.EntityEvent.Type == 1){
$.each(data.EntityEvent.Entities, function(i, entity){
//TODO: 处理实体类更新
if(i == data.EntityEvent.Entities.length - 1){
getEvent();
}
});
return;
}
//Delete
if(data.EntityEvent.Type == 2){
$.each(data.EntityEvent.Entities, function(i, entity){
//TODO: 处理实体类删除
if(i == data.EntityEvent.Entities.length - 1){
getEvent();
}
});
}
}else{
$("#imageSets").hoverList("add", data);
getEvent();
}
});
};
getEvent();
});