• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
皇图霸业谈笑间
更高、更快、更强
博客园    首页    新随笔    联系   管理    订阅  订阅
减少服务器流量问题

问题描述,看书文件下载服务器不断提供书籍章节内容信息给 看书服务器

导致网卡流量飚高 , 现在通过传输过程对数据进行压缩的方式解决这个问题

 

下面是压缩和解压缩代码

 

 

 static string CompressString(string input)
        {
            
string retValue = string.Empty;
            
if (!string.IsNullOrEmpty(input))
            {
                
byte[] byteSource = Encoding.UTF8.GetBytes(input);
                MemoryStream msm 
= new MemoryStream();
                
using (GZipStream gzs = new GZipStream(msm, CompressionMode.Compress, true))
                {
                    gzs.Write(byteSource, 
0, byteSource.Length);
                }

                msm.Position 
= 0;

                
byte[] compBytes = new byte[msm.Length];
                msm.Read(compBytes, 
0, compBytes.Length);

                msm.Close();

                
byte[] finalBuffer = new byte[compBytes.Length + 4];
                Buffer.BlockCopy(compBytes, 
0, finalBuffer, 4, compBytes.Length);
                Buffer.BlockCopy(BitConverter.GetBytes(byteSource.Length), 
0, finalBuffer, 0, 4);

                retValue 
= System.Convert.ToBase64String(finalBuffer);
            }

            
return retValue;
        }




static string DecompressString(string input)
    {
        
string retValue = string.Empty;
        
if (!string.IsNullOrEmpty(input))
        {
            
byte[] source = System.Convert.FromBase64String(input);
            
using (MemoryStream msm = new MemoryStream())
            {
                
int length = BitConverter.ToInt32(source, 0);
                msm.Write(source, 
4, source.Length - 4);

                
//Console.WriteLine(Encoding.UTF8.GetString(source));

                msm.Position 
= 0;
                
byte[] decmpBytes = new byte[length];
                
using (GZipStream gzs = new GZipStream(msm, CompressionMode.Decompress))
                {
                    gzs.Read(decmpBytes, 
0, length);

                    
//gzs.CopyTo();
                }

                retValue 
= Encoding.UTF8.GetString(decmpBytes);
            }
        }

        
return retValue;
    }
posted on 2011-07-22 12:51  布颜书  阅读(247)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3