Commet技术,是2000年左右诞生的基于HTTP长连接,服务器向客户端(浏览器)推送数据的一种技术。 目前,websocket技术为此类问题的最优解决方案,C# 也有SignalIR专门用于解决服务器主动向客户端主动推送的问题。

comet sequence diagram

  • 订阅客户端发送订阅请求,发布客户端推送信息,服务器将推送信息转发至订阅客户端
  • 订阅客户端未发起订阅请求,发布客户端推送消息,服务器将消息缓存,带订阅客户端订阅请求到来时转发给订阅客户端
  • 订阅客户端订阅请求超时,仍未有新消息推送,则服务器返回超时

实现

  • 客户端初始化,分配一个缓存消息队列
  • 接收订阅请求后,异步启动遍历消息队列线程循环检查缓存消息队列中是否有消息和是否超时,有消息或超时则返回异步应答订阅请求
  • 发布过程即投递至缓存消息队列中

优化

  • HTTP 请求和应答采取异步
  • 使用独立线程池或者与http服务器请求应答处理线程公用线程池
  • 消息队列采用NoSQL数据库缓存

参考

标签: http, csharp
日期: 2018-06-01 17:30:06, 6 years and 228 days ago
using ComponentAce.Compression.Libs.zlib;
namespace zlibdemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Action inflation = () =>
             {
                 string hizlib = "hi,zlib!";
                 FileStream zip = new FileStream(args[0], System.IO.FileMode.Create);
                 ZOutputStream o = new ZOutputStream(zip, zlibConst.Z_DEFAULT_COMPRESSION);
                 Stream s = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(hizlib));
                 try
                 {
                     Action< Stream, Stream > copyStream = (Stream input, Stream output) =>
                     {
                         byte[] buffer = new byte[4096];
                         int len;
                         while ((len = input.Read(buffer, 0, 4096)) > 0)
                         {
                             output.Write(buffer, 0, len);
                         }
                         output.Flush();
                     };
                     copyStream(s, o);
                 }
                 finally
                 {
                     o.Close();
                     zip.Close();
                     s.Close();
                 }
             };
            inflation();
            Action deflation = () =>
            {
                FileStream zip = new System.IO.FileStream(args[0], System.IO.FileMode.Open);
                FileStream txt = new System.IO.FileStream(args[1], System.IO.FileMode.Create);
                ZInputStream unzip = new ZInputStream(zip);
                try
                {
                    Action< ZInputStream, Stream > copyStream = (ZInputStream input, Stream output) =>
                    {
                        byte[] buffer = new byte[4096];
                        int len;
                        while ((len = input.read(buffer, 0, 4096)) > 0)
                        {
                            output.Write(buffer, 0, len);
                        }
                        output.Flush();
                    };
                    copyStream(unzip, txt);
                }
                finally
                {
                    unzip.Close();
                    txt.Close();
                    zip.Close();
                }
            };
            deflation();
        }
    }
}

sample

reference

zlib home site ZLIB for .NET

标签: csharp
日期: 2017-02-20 17:30:06, 7 years and 329 days ago