准备工作
1.新建一个工程,添加一个WCF服务库, 然后公共的类库, 添加一个默认可序列化的的CompositeType类用于压缩。
[Serializable] public class CompositeType { bool boolValue = true; string stringValue = "Hello "; public bool BoolValue { get { return boolValue; } set { boolValue = value; } } public string StringValue { get { return stringValue; } set { stringValue = value; } } }
2.在默认的服务接口中添加一个测试接口用于测试数据传输
[ServiceContract] public interface IService1 { [OperationContract] byte[] GetByteTest(byte[] byt); }
实现>.
public class Service1 : IService1 { public byte[] GetByteTest(byte[] objectArrar) { //解压客户端返回数据 Common.CompositeType user = (Common.CompositeType)ZipTools.DecompressionObject(objectArrar); //压缩当前解压数据 return ZipTools.CompressionObject(user); } }
示例中用到的压缩解压具体实现如下:
/// <summary> /// 压缩方法 /// </summary> /// <param name="DataOriginal"></param> /// <returns></returns> public static byte[] CompressionObject(object DataOriginal) { if (DataOriginal == null) return null; BinaryFormatter bFormatter = new BinaryFormatter(); MemoryStream mStream = new MemoryStream(); bFormatter.Serialize(mStream, DataOriginal); byte[] bytes = mStream.ToArray(); MemoryStream oStream = new MemoryStream(); DeflateStream zipStream = new DeflateStream(oStream, CompressionMode.Compress); zipStream.Write(bytes, , bytes.Length); zipStream.Flush(); zipStream.Close(); return oStream.ToArray(); } /// <summary> /// 解压方法 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static object DecompressionObject(byte[] bytes) { if (bytes == null) return null; MemoryStream mStream = new MemoryStream(bytes); mStream.Seek(, SeekOrigin.Begin); DeflateStream unZipStream = new DeflateStream(mStream, CompressionMode.Decompress, true); object dsResult = null; BinaryFormatter bFormatter = new BinaryFormatter(); dsResult = (object)bFormatter.Deserialize(unZipStream); return dsResult; }
服务端已经完成, 挂载发布, 可以新建一个客户端控制进行数据测试 ~
新建一个控制台应用程序, 添加引用发布的WCF服务测试地址, 添加客户端代码:
示例:提交 最开启新建的类经过压缩处理 服务端再把请求的信息返回, 用于测试验证, 如下
class Program { static void Main(string[] args) { ServiceReference1.Service1Client client = new ServiceReference1.Service1Client(); //本地压缩数据提交字节数据 byte[] ServiceArray = client.GetByteTest(ZipTools.CompressionObject(new Common.CompositeType() { BoolValue = true, StringValue = "测试数据" })); //解压服务端字节数据 CompositeType cmp = (CompositeType)ZipTools.DecompressionObject(ServiceArray); Console.WriteLine("返回数据打印列表:"); Console.WriteLine(cmp.BoolValue); Console.WriteLine(cmp.StringValue); Console.ReadKey(); } }
请求示例结果: