英文原文:http://www.networkcomms.net/custom-objects/
NetworkComms.Net网络库,支持发送自定义类,并可以在序列化时进行压缩和加密。序列化我们通常使用开源的Protobuf.net类库,也可以使用别的序列化方式。
简单的回顾一下,发送自定义类【契约类】的语法如下:
1、首先定义契约类,(以使用protobuf.net序列化器为例)
1 [ProtoContract]
2 private class CustomObject
3 {
4 [ProtoMember(1)]
5 public int Age { get; private set; }
6
7 [ProtoMember(2)]
8 public string Name { get; private set; }
9
10 /// <summary>
11 /// Parameterless constructor required for protobuf
12 /// </summary>
13 protected CustomObject() { }
14
15 public CustomObject(string name, int age)
16 {
17 this.Name = name;
18 this.Age = age;
19 }
20 }
2、实例化契约类,并用某个Tcp连接发送
1
2 CustomObject myCustomObject = new CustomObject("ben", 25);
3 tcpConn.SendObject("Message", "127.0.0.1", 10000, myCustomObject);
4
5
契约类中,可以包含值类型、集合类型等原始数据类型。
某些类型没有设计为可以使用protobuf-net进行序列化,就需要做更多的工作。
下面以 Image类为例:
1 [ProtoContract]
2 public class ImageWrapper
3 {
4 /// <summary>
5 /// 把Image对象存储为私有的字节数组
6 /// </summary>
7 [ProtoMember(1)]
8 private byte[] _imageData;
9
10 /// <summary>
11 /// 图片名称
12 /// </summary>
13 [ProtoMember(2)]
14 public string ImageName { get; set; }
15
16 /// <summary>
17 /// 图片对象
18 /// </summary>
19 public Image Image { get; set; }
20
21 /// <summary>
22 /// 私有的无参数构造函数 反序列化时需要使用
23 /// </summary>
24 private ImageWrapper() { }
25
26 /// <summary>
27 /// 创建一个新的 ImageWrapper类
28 /// </summary>
29 /// <param name="imageName"></param>
30 /// <param name="image"></param>
31 public ImageWrapper(string imageName, Image image)
32 {
33 this.ImageName = imageName;
34 this.Image = image;
35 }
36
37 /// <summary>
38 ///序列化之前,把图片转化为二进制数据
39 /// </summary>
40 [ProtoBeforeSerialization]
41 private void Serialize()
42 {
43 if (Image != null)
44 {
45 //We need to decide how to convert our image to its raw binary form here
46 using (MemoryStream inputStream = new MemoryStream())
47 {
48 //For basic image types the features are part of the .net framework
49 Image.Save(inputStream, Image.RawFormat);
50
51 //If we wanted to include additional data processing here
52 //such as compression, encryption etc we can still use the features provided by NetworkComms.Net
53 //e.g. see DPSManager.GetDataProcessor<LZMACompressor>()
54
55 //Store the binary image data as bytes[]
56 _imageData = inputStream.ToArray();
57 }
58 }
59 }
60
61 /// <summary>
62 /// 反序列化时,把二进制数据转化为图片对象
63 /// </summary>
64 [ProtoAfterDeserialization]
65 private void Deserialize()
66 {
67 MemoryStream ms = new MemoryStream(_imageData);
68
69 //If we added custom data processes we have the perform the reverse operations here before
70 //trying to recreate the image object
71 //e.g. DPSManager.GetDataProcessor<LZMACompressor>()
72
73 Image = Image.FromStream(ms);
74 _imageData = null;
75 }
76 }
www.networkcomms.cn编辑
www.cnblogs.com/networkcomms