标签:
能够发送自定义对象,并且在发送的时候对发送的对象进行加密,压缩是networkComms v3框架的一个重要特性。
具体可以参考源码中 ExampleConsole 工程文件
使用NetworkComms V3 框架发送自定义对象的语法如下:
CustomObject myCustomObject = new CustomObject("ben", 25); NetworkComms.SendObject("Message", "127.0.0.1", 10000, myCustomObject);
如果您使用的是protobuf.net序列化器,那么自定义对象的语法如下:
[ProtoContract] private class CustomObject { [ProtoMember(1)] public int Age { get; private set; } [ProtoMember(2)] public string Name { get; private set; } /// <summary> /// Parameterless constructor required for protobuf /// </summary> protected CustomObject() { } public CustomObject(string name, int age) { this.Name = name; this.Age = age; } }
对于一些不支持序列化的类,比如image 类的序列化,要进行一些转换,如下:
[ProtoContract] public class ImageWrapper { /// <summary> /// Private store of the image data as a byte[] /// This will be populated automatically when the object is serialised /// </summary> [ProtoMember(1)] private byte[] _imageData; /// <summary> /// The image name /// </summary> [ProtoMember(2)] public string ImageName { get; set; } /// <summary> /// The public accessor for the image. This will be populated /// automatically when the object is deserialised. /// </summary> public Image Image { get; set; } /// <summary> /// Private parameterless constructor required for deserialisation /// </summary> private ImageWrapper() { } /// <summary> /// Create a new ImageWrapper /// </summary> /// <param name="imageName"></param> /// <param name="image"></param> public ImageWrapper(string imageName, Image image) { this.ImageName = imageName; this.Image = image; } /// <summary> /// Before serialising this object convert the image into binary data /// </summary> [ProtoBeforeSerialization] private void Serialize() { if (Image != null) { //We need to decide how to convert our image to its raw binary form here using (MemoryStream inputStream = new MemoryStream()) { //For basic image types the features are part of the .net framework Image.Save(inputStream, Image.RawFormat); //If we wanted to include additional data processing here //such as compression, encryption etc we can still use the features provided by NetworkComms.Net //e.g. see DPSManager.GetDataProcessor<LZMACompressor>() //Store the binary image data as bytes[] _imageData = inputStream.ToArray(); } } } /// <summary> /// When deserialising the object convert the binary data back into an image object /// </summary> [ProtoAfterDeserialization] private void Deserialize() { MemoryStream ms = new MemoryStream(_imageData); //If we added custom data processes we have the perform the reverse operations here before //trying to recreate the image object //e.g. DPSManager.GetDataProcessor<LZMACompressor>() Image = Image.FromStream(ms); _imageData = null; } }
原文:http://www.networkcomms.net/custom-objects/
www.networkcomms.cn整理
标签:
原文地址:http://www.cnblogs.com/networkcomms/p/4322182.html