提高WCF的吞吐效率

 
  
1 using System;
2 using System.Collections.Generic;
3 using System.IO;
4 using System.IO.Compression;
5 using System.Linq;
6 using System.Text;
7 using System.Runtime.Serialization.Formatters.Binary;
8
9 namespace Kingge.Mini.Network
10 {
11 /// <summary>
12 /// 压缩工具类,可以用于减小流量,提升传输效率
13 /// </summary>
14 public static class DeflateUtil
15 {
16 /// <summary>
17 /// 还原对象信息
18 /// </summary>
19 /// <param name="bytes"> 字节数组 </param>
20 public static object GetObject( byte [] bytes)
21 {
22 if (bytes == null || bytes.Length == 0 )
23 {
24 return null ;
25 }
26 using (MemoryStream memory = new MemoryStream(bytes))
27 {
28 int first = memory.ReadByte();
29 // 判断标记位,0直接还原,1先解压再还原
30 if (first == 0 )
31 {
32 BinaryFormatter formatter = new BinaryFormatter();
33 return formatter.Deserialize(memory);
34 }
35 else
36 {
37 using (DeflateStream deflate = new DeflateStream(memory,CompressionMode.Decompress, true ))
38 {
39 BinaryFormatter formatter = new BinaryFormatter();
40 return formatter.Deserialize(deflate);
41 }
42 }
43 }
44 }
45
46 /// <summary>
47 /// 压缩对象
48 /// </summary>
49 /// <param name="obj"> 被压缩对象 </param>
50 public static byte [] DeflateObject( object obj)
51 {
52 if (obj == null )
53 {
54 return null ;
55 }
56 // 值类型或者字符串没有压缩的必要
57 if (obj.GetType().IsValueType || obj is string )
58 {
59 using (MemoryStream memory = new MemoryStream())
60 {
61 // 写入标记位0,表示未经过压缩
62 memory.WriteByte(( byte ) 0 );
63 BinaryFormatter formatter = new BinaryFormatter();
64 formatter.Serialize(memory,obj);
65 memory.Position = 0 ;
66 return memory.ToArray();
67 }
68 }
69 else
70 {
71 using (MemoryStream memory = new MemoryStream())
72 {
73 // 写入标记位1,表示经过压缩
74 memory.WriteByte(( byte ) 1 );
75 using (DeflateStream deflate = new DeflateStream(memory,CompressionMode.Compress, true ))
76 {
77 BinaryFormatter formatter = new BinaryFormatter();
78 formatter.Serialize(deflate, obj);
79 }
80 memory.Position = 0 ;
81 return memory.ToArray();
82 }
83 }
84 }
85 }
86 }

转载于:https://www.cnblogs.com/kingge/archive/2011/05/09/2040876.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值