COMET彗星(三)构建自己的COMET核心

主题列表:

COMET彗星(一)SERVER PUSH介绍

COMET彗星(二)基于SERVER PUSH的消息传输

引言:

      在上一篇随笔中,对COMET使用的类和作用进行了简短的介绍,从本篇随笔开始,将从实体类开始,对COMET的核心进行构建分析。

CORE框架:

      

图1.1 COMET核心框架

CometMessage类:

     CometMessage类是COMET的通信载体,对消息的主体进行抽象,实际上这个类是最容易进行扩展的,因为从设计上看,它只是一个消息的容器。而诸如地理坐标,业务数据等,都可以通过这个类来进行直接扩充。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace MethodWorx.AspNetComet.Core { /// <summary> /// CometMessage Class /// /// This is a CometMessage that has been sent to the client, the DataContract names have been /// shortened to remove any bytes we dont need from the message (ok, did'nt save much, but we can do it!) /// </summary> [DataContract(Name="cm")] public class CometMessage { [DataMember(Name="mid")] private long messageId; [DataMember(Name="n")] private string name; [DataMember(Name="c")] private object contents; /// <summary> /// Gets or Sets the MessageId, used to track which message the Client last received /// </summary> public long MessageId { get { return this.messageId; } set { this.messageId = value; } } /// <summary> /// Gets or Sets the Content of the Message /// </summary> public object Contents { get { return this.contents; } set { this.contents = value; } } /// <summary> /// Gets or Sets the error message if this is a failure /// </summary> public string Name { get { return this.name; } set { this.name = value; } } } }

 

      类的设计简单明了,这里有必要解释下使用System.Runtime.Serialization命名空间的意义。

      “System.Runtime.Serialization 命名空间包含可用于将对象序列化和反序列化的类。序列化是将对象或对象图形转换为线性字节序列,以存储或传输到另一个位置的过程。反序列化是接受存储的信息并利用它重新创建对象的过程。”

      这是MSDN给我们的解释,将对象转变为线性字节,然后方便传输与调用。当然这个例子中的数据类型并不复杂,但也包含了LONG,OBJECT,STRING这样的数据类型。其中Contents成员为object对象,这给我们留下了非常大的想像空间。(图片?复杂对象类型?自定义对象类型?……)

 

CometClient类:

      CometClient类是对客户端信息的抽象类,同时包含了两个关键属性ConnectionIdleSeconds和ConnectionTimeoutSeconds。由于考虑到不同客户端间传递属性,仍然使用System.Runtime.Serialization来序列化信息。

      关于JSON的应用,这个框架其实也提供了相应支持。后面的随笔中我会介绍。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace MethodWorx.AspNetComet.Core { /// <summary> /// CometClient Class /// /// This represents a logged in client within the COMET application. This marked as a DataContract becuase /// it can be seralized to the client using JSON /// </summary> [DataContract] public class CometClient { [DataMember] private string privateToken; [DataMember] private string publicToken; [DataMember] private string displayName; [DataMember] private DateTime lastActivity; [DataMember] private int connectionIdleSeconds; [DataMember] private int connectionTimeoutSeconds; /// <summary> /// Gets or Sets the token used to identify the client to themselves /// </summary> public string PrivateToken { get { return this.privateToken; } set { this.privateToken = value; } } /// <summary> /// Gets or Sets the token used to identify the client to other clients /// </summary> public string PublicToken { get { return this.publicToken; } set { this.publicToken = value; } } /// <summary> /// Gets or Sets the display name of the client /// </summary> public string DisplayName { get { return this.displayName; } set { this.displayName = value; } } /// <summary> /// Gets or Sets the last activity of the client /// </summary> public DateTime LastActivity { get { return this.lastActivity; } set { this.lastActivity = value; } } /// <summary> /// Gets or Sets the ConnectionIdleSections property which is the number of seconds a connection will remain /// alive for without being connected to a client, after this time has expired the client will /// be removed from the state manager /// </summary> public int ConnectionIdleSeconds { get { return this.connectionIdleSeconds; } set { this.connectionIdleSeconds = value; } } /// <summary> /// Gets or Sets the ConnectionTimeOutSections property which is the number of seconds a connection will remain /// alive for whilst being connected to a client, but without receiving any messages. After a timeout has expired /// A client should restablish a connection to the server /// </summary> public int ConnectionTimeoutSeconds { get { return this.connectionTimeoutSeconds; } set { this.connectionTimeoutSeconds = value; } } } }

ConnectionIdleSeconds:用来设置连接线程,当connection断线后,后台Thread的存活时间。

ConnectionTimeoutSeconds:客户端的超时时间,当超过时间后,客户端重新连接服务器。

ps:有这两个属性后,基本上完成了客户端连接的控制,超时重连接,无连接时杀死后台线程。

ICometStateProvider接口:

     ICometStateProvider接口直接被CometStateMessager建立,这样的好处是实例化CometStateMessager对象后,CometStateMessager对象可以直接调用ICometStateProvider接口的实现,实际上实现了Adapter的方式,我们可以定制不同的InProcCometStateProvider类(在下面会提到)来定制自己的接口。

      ICometStateProvider接口类提供了如下几个接口。

 

      InitializeClient:提供ComentClient的初始化操作。

      GetMessages:得到一个Messages的消息队列。

      SendMessage:发送Message数据。

      SendMessage:可以针对Client name来进行消息发布(私人会话)。

      GetCometClient:返回一个Client。

      KillIdleCometClient:杀掉一个无效的Client对象。

 

      ps:当然这个接口是可以被拓展的,而且实现起来非常简单。得到Client队列信息,得到Client状态等等。甚至你可以想象一些更复杂的应用(比如加入一个流媒体消息……)。

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MethodWorx.AspNetComet.Core { /// <summary> /// This interface can be implemented to provide a custom state provider /// for the CometStateManager class. Typical examples may be using SqlServer /// to enable the operation over a server farm /// </summary> public interface ICometStateProvider { /// <summary> /// Implementation of this method should store the cometClient instance in some sort /// of cache (eg Memory, Db etc..) /// </summary> /// <param name="cometClient"></param> void InitializeClient(CometClient cometClient); /// <summary> /// Imeplementation of this method should return all the messages that are queued /// for a specific client, it is only interested in messages that have a greater id than /// lastMessageId /// </summary> /// <param name="clientPrivateToken"></param> /// <param name="lastMessageId"></param> /// <returns></returns> CometMessage[] GetMessages(string clientPrivateToken, long lastMessageId); /// <summary> /// Implementation of this method should queue a message for the specific client /// </summary> /// <param name="clientPublicToken"></param> /// <param name="name"></param> /// <param name="contents"></param> void SendMessage(string clientPublicToken, string name, object contents); /// <summary> /// Implementation of this method should queue a message for all the clients /// </summary> /// <param name="name"></param> /// <param name="contents"></param> void SendMessage(string name, object contents); /// <summary> /// Implementation of this method should return a specific comet client /// </summary> /// <param name="clientPrivateToken"></param> /// <returns></returns> CometClient GetCometClient(string clientPrivateToken); /// <summary> /// Implementation of this method should remove a client from the cache /// </summary> /// <param name="clientPrivateToken"></param> void KillIdleCometClient(string clientPrivateToken); } }

InProcCometStateProvider类:

      InProcCometStateProvider类实现了ICometStateProvider接口,并且提供了一个很好的范例,针对这个类,我们可以想象很多很好的拓展,诸如调用AO组件,封装报警信息等等。

      InProcCometStateProvider类包含类一个私有的内部类InProcCometStateProvider,实际上可以理解为一种对消息的简单封装,设计的时候考虑到需要关联CometClient和Message,其实也可以单独作为一个外部类来设计。不过Adapter本身不应该太多关联类,这样做也是权衡了一些拓展上的需求。

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MethodWorx.AspNetComet.Core { /// <summary> /// Class InProcCometStateProvider /// /// This class provides an implementation of ICometStateProvider that keeps the /// information in memory. This provider is not scalable as it will not run on a server /// farm but demonstrates how you should implemement the provider. /// </summary> public class InProcCometStateProvider : ICometStateProvider { /// <summary> /// Private class which holds the state of each connected client /// </summary> private class InProcCometClient { public CometClient CometClient; public Dictionary<long, CometMessage> Messages = new Dictionary<long, CometMessage>(); public long NextMessageId = 1; } /// <summary> /// Cache of clients /// </summary> private Dictionary<string, InProcCometClient> publicClients = new Dictionary<string, InProcCometClient>(); private Dictionary<string, InProcCometClient> privateClients = new Dictionary<string, InProcCometClient>(); private static object state = new object(); #region ICometStateProvider Members /// <summary> /// Store the new client in memory /// </summary> /// <param name="cometClient"></param> public void InitializeClient(CometClient cometClient) { if (cometClient == null) throw new ArgumentNullException("cometClient"); lock (state) { // ok, ensure we dont already exist if (publicClients.ContainsKey(cometClient.PublicToken) || privateClients.ContainsKey(cometClient.PrivateToken)) throw CometException.CometClientAlreadyExistsException(); InProcCometClient inProcCometClient = new InProcCometClient() { CometClient = cometClient }; // stick the client int he arrays // ready to be used publicClients.Add(cometClient.PublicToken, inProcCometClient); privateClients.Add(cometClient.PrivateToken, inProcCometClient); } // ok, they are in there ready to be used } /// <summary> /// Get the messages for a specific client /// </summary> /// <param name="clientPrivateToken"></param> /// <param name="lastMessageId"></param> /// <returns></returns> public CometMessage[] GetMessages(string clientPrivateToken, long lastMessageId) { if(string.IsNullOrEmpty(clientPrivateToken)) throw new ArgumentNullException("clientPrivateToken"); lock (state) { if (!privateClients.ContainsKey(clientPrivateToken)) throw CometException.CometClientDoesNotExistException(); // // ok, get the client InProcCometClient cometClient = privateClients[clientPrivateToken]; List<long> toDelete = new List<long>(); List<long> toReturn = new List<long>(); // wicked, we have the client, so we can get its messages from our list // we delete any before the last messageId becuase we dont want them foreach(long key in cometClient.Messages.Keys) { if(key <= lastMessageId) toDelete.Add(key); else toReturn.Add(key); } // delete the ones from the messages foreach (long key in toDelete) { cometClient.Messages.Remove(key); } // and return the ones in the toReturn array List<CometMessage> cometMessages = new List<CometMessage>(); foreach (long key in toReturn) { cometMessages.Add(cometClient.Messages[key]); } return cometMessages.ToArray(); } } /// <summary> /// Send a message to a specific client /// </summary> /// <param name="clientPublicToken"></param> /// <param name="name"></param> /// <param name="contents"></param> public void SendMessage(string clientPublicToken, string name, object contents) { if (string.IsNullOrEmpty(clientPublicToken)) throw new ArgumentNullException("clientPublicToken"); if (contents == null) throw new ArgumentNullException("contents"); lock (state) { if (!publicClients.ContainsKey(clientPublicToken)) throw CometException.CometClientDoesNotExistException(); // // ok, get the client InProcCometClient cometClient = publicClients[clientPublicToken]; // ok, stick the message in the array CometMessage message = new CometMessage(); message.Contents = contents; message.Name = name; message.MessageId = cometClient.NextMessageId; // increment cometClient.NextMessageId++; cometClient.Messages.Add(message.MessageId, message); } } /// <summary> /// Send a message to all the clients /// </summary> /// <param name="name"></param> /// <param name="contents"></param> public void SendMessage(string name, object contents) { if (contents == null) throw new ArgumentNullException("contents"); lock (state) { foreach (InProcCometClient cometClient in publicClients.Values) { // ok, stick the message in the array CometMessage message = new CometMessage(); message.Contents = contents; message.Name = name; message.MessageId = cometClient.NextMessageId; // increment cometClient.NextMessageId++; cometClient.Messages.Add(message.MessageId, message); } } } /// <summary> /// Get the client from the state provider /// </summary> /// <param name="clientPrivateToken"></param> /// <returns></returns> public CometClient GetCometClient(string clientPrivateToken) { if (!this.privateClients.ContainsKey(clientPrivateToken)) throw CometException.CometClientDoesNotExistException(); // return the client private token return this.privateClients[clientPrivateToken].CometClient; } /// <summary> /// Remove an idle client from the memory /// </summary> /// <param name="clientPrivateToken"></param> public void KillIdleCometClient(string clientPrivateToken) { if (!this.privateClients.ContainsKey(clientPrivateToken)) throw CometException.CometClientDoesNotExistException(); // get the client InProcCometClient ipCometClient = this.privateClients[clientPrivateToken]; // and remove the dictionarys this.privateClients.Remove(ipCometClient.CometClient.PrivateToken); this.publicClients.Remove(ipCometClient.CometClient.PublicToken); } #endregion } }

 

PS:可以说这篇随笔中将COMET IM的几个最容易拓展的类进行了介绍,核心部分将在下一篇随笔中进行讲解,欢迎大家讨论并拍砖。同时预祝大家春节愉快!

转载于:https://www.cnblogs.com/lzlynn/archive/2009/01/21/1379575.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/363399.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何在JavaServer Pages中使用Salesforce REST API

摘要&#xff1a;本教程提供了一个JSP示例以及如何将其与Salesforce REST API集成。 我们将逐步完成创建外部客户端以使用Force.com &#xff08;同时使用HTTP&#xff08;S&#xff09;和JSON&#xff09;管理您的数据的分步过程。 在此示例中&#xff0c;我将Mac OS X 10.9.…

写在08年“愚人节”

从博客园学了很多东西&#xff0c;是时候该回馈了。谢谢博客园给我们提供这么好的平台交流技术。 刚发了文章习惯性的看了下自己博客的首页代码&#xff0c;感觉日历不够精良。 我做过的一个ajax日历&#xff0c;可以参考解放日报 艺术家具版的日期直达功能的日历&#xff0c;用…

19.3.20 解决pycharm快捷键无法使用问题和熟悉git与码云操作流程

problem&#xff1a;由于Vim插件导致快捷键无法使用&#xff1b; answer&#xff1a;settings→Plugins→搜索到ideaVim→取消选中→apply→重启pycharm&#xff1b; git&#xff1a;创建仓库→生成公钥&#xff08;ssh-keygen -t rsa -C "962891994qq.com"&#xff…

JQuery实现点击按钮切换图片(附源码)--JQuery基础

JQuery实现切换图片相对比较简单&#xff0c;直接贴代码了哈&#xff0c;有注释噢&#xff01;疑问请追加评论哈&#xff0c;不足之处还请大佬们指出&#xff01; 1、案例代码&#xff1a; demo.html&#xff1a; <!DOCTYPE html><html><head>   <me…

Java EE陷阱#1:忽略@Singleton的默认锁定

EJB Singleton Bean是EJB 3.1规范引入的&#xff0c;通常用于存储缓存的数据。 这意味着&#xff0c;我们尝试通过使用Singleton来提高应用程序的性能。 总的来说&#xff0c;这很好。 特别是在并行调用不多的情况下。 但是&#xff0c;如果我们忽略默认锁&#xff0c;并且并行…

js左右对联

相当着急的找了一早上&#xff0c;幸好有原来的代码作为基础&#xff0c;不害怕。<script>function initEcAd() {document.all.AdLayer1.style.posTop -200;document.all.AdLayer1.style.visibility visibledocument.all.AdLayer2.style.posTop -200;document.all.AdL…

cocos2d-x 横屏、竖屏(以及基于传感器)、读写sd卡

一、横屏、竖屏设置&#xff08;以及基于传感器的&#xff09; AndroidManifest.xml文件中&#xff0c; 1、不论任何情况的&#xff1a; screenOrientation"landscape" 为横屏 screenOrientation"portrait"为竖屏 …

CSS3盒子模型

web前端必须了解的CSS3盒子模型 1、需要了解的属性以及属性值 display:box或者display:inline-box box-orient:horizontal | vertical (水平 垂直) 定义盒模型的布局方向 box-direction:normal reverse(正序 反序) 元素排列顺序 box-ordinal-group:number(数值) 设置元素…

与JBoss Fuse,Jenkins和Nexus的持续集成

最近&#xff0c;我正在整理一个快速启动的Maven项目&#xff0c;以展示一种组织JBoss Fuse项目的可行方法。 该项目可在Github上找到&#xff1a; https &#xff1a; //github.com/paoloantinori/fuse_ci 这是我与朋友詹姆斯罗林斯 &#xff08; James Rawlings&#xff09…

回家

好啦&#xff0c;搞笑的2008年过去了&#xff0c;拿完年终奖&#xff0c;回家过年吧。 去年这个年还真有意思&#xff0c;先有冰冻&#xff0c;后有地震&#xff0c;还有奥运。 好的也有&#xff0c;坏的也有&#xff0c;不过不管怎么样&#xff0c;我们还是撑过来了。 08年也没…

HDFS优缺点

HDFS架构简述 一、HDFS简介 HDFS&#xff08;Hadoop distributed File System&#xff09;&#xff1a;Hadoop分布式文件系统。是基于流数据模式访问和处理超大文件的需要而开发的&#xff0c;可以运行于廉价的服务器上。它所具有的高容错&#xff0c;高可靠性&#xff0c;高可…

Python学习_线程Thread学习 GIL锁 队列queue 线程池

进程和线程的目的&#xff1a;提高执行效率IO操作利用极少量CPUIO密集型(不用CPU)&#xff1a;多线程计算密集型(用CPU)&#xff1a;多进程1、单进程单线程&#xff0c;主进程&#xff0c;主线程2、自定义线程&#xff1a; 主进程&#xff1a; 主线程 子线程进…

html5表单与PHP交互

1、示例代码 前端&#xff1a; <!DOCTYPE html><html><head><meta charset"utf-8"> <title>html5表单与PHP交互</title></head><body><form action"http://localhost/jh.php" method"post"…

文件加密 1

一、 1、NTFS分区才能使用EFS加密&#xff1b; 2、我的电脑&#xff0d;&#xff0d;工具&#xff0d;&#xff0d;文件夹选项&#xff0d;&#xff0d;查看&#xff0d;&#xff0d;取消简单文件共享&#xff1b; 3、右键点击要加密的文件或文件夹&#xff0d;&#xff0d;属性…

Java中抽象类和接口之间的区别

一些受欢迎的访谈问题是“抽象类和接口之间有什么区别”&#xff0c;“什么时候使用抽象类以及什么时候使用接口”。 因此&#xff0c;在本文中&#xff0c;我们将讨论这个主题。 在探讨它们之间的差异之前&#xff0c;让我们先介绍一下它们。 抽象类 创建抽象类以捕获子类的…

【DP】【期望】$P1850$换教室

【DP】【期望】\(P1850\)换教室 链接 题目描述 有 \(2n\) 节课程安排在$ n$ 个时间段上。在第 \(i\)&#xff08;\(1 \leq i \leq n\)&#xff09;个时间段上&#xff0c;两节内容相同的课程同时在不同的地点进行&#xff0c;其中&#xff0c;牛牛预先被安排在教室 \(c_i\)上课…

封装cookie设置和获取的简易方法

(function() {var tool {expires: "expires", // 过期时间expirespath: "path", // 路径domain: "domain", // 域secure: "secure" // 安全设置 bool};//设置function setCookie(k, v, options) {if (!options) {document.cookie k…

高并发服务器逻辑处理瓶颈,如何解决?

https://mp.weixin.qq.com/s/GHHHvgURdZpNJ1Ec6RHgPg 高并发衡量指标 响应时间&#xff1a;系统对请求做出响应的时间&#xff0c;即一个http请求返回所用的时间&#xff1b;吞吐量&#xff1a;单位时间内处理的请求数量&#xff1b;QPS&#xff08;TPS&#xff09;&#xff1a…

Oracle学习笔记:blank_trimming的含义

blank_trimming 静态初始化参数控制 【字符串的尾随空格】是否自动截断&#xff01;以便【字符类型】的 【列】或【变量】之间在运算时不用考虑尾随空格的长度&#xff01;这样就和sql-92的标准兼容了 例子&#xff1a; DECLARE v_char1 VARCHAR2(2); v_char2 VARCHAR2(…

InterruptedException和中断线程的说明

如果没有将InterruptedException检查为异常&#xff0c;则可能甚至没人会注意到它-这实际上可以防止这些年来的几个错误。 但是由于必须对其进行处理&#xff0c;因此许多人不正确或不加考虑地处理它。 让我们以一个线程的简单示例为例&#xff0c;该线程定期进行一些清理&…