什么是用于创建C#中的网络数据包的结构/类的最好方法?

问题描述:

我不知道是否有解释来处理在C#中的网络数据包通信的最佳方法什么好导游或书籍?

I'm wondering if there are any good guides or books that explain the best way to handle network packet communication in C#?

现在,我使用的是结构和基于该结构的值的字节数组的方法。

Right now I'm using a structure and a method that generates a byte array based on values of the structure.

有没有一种简单的方法来做到这一点?甚至更好的办法

Is there a simpler way to do this? Or even a better way?

public struct hotline_transaction
{
        private int transaction_id;
        private short task_number;
        private int error_code;
        private int data_length;
        private int data_length2;



...

...

    	public int Transaction_id
    	{
    		get
    		{
    			return IPAddress.HostToNetworkOrder(transaction_id);
    		}
    		set
    		{
    			transaction_id = value;
    		}
    	}



...

...

    	public byte[] GetBytes()
    	{
    		List<byte> buffer = new List<byte>();
    		buffer.Add(0); // reserved
    		buffer.Add(0); // request = 0

    		buffer.AddRange(BitConverter.GetBytes(Task_number));
    		buffer.AddRange(BitConverter.GetBytes(Transaction_id));
    		buffer.AddRange(BitConverter.GetBytes(error_code));


    		buffer.AddRange(BitConverter.GetBytes(Data_length));

    		buffer.AddRange(subBuffer.ToArray());

    		return buffer.ToArray(); // return byte array for network sending
    	}
}



除此之外,是有一个很好的指南或文章分析网络数据转化为有用的结构/类的最佳实践?

Beyond that is there a good guide or article on the best practice of parsing network data into usable structures / classes?

你有没有听说过谷歌协议缓冲区?

协议缓冲区是
谷歌为他们的大部分数据
通信所使用的
二进制序列化格式的名称。它的设计是:

protocol buffers is the name of the binary serialization format used by Google for much of their data communications. It is designed to be:

小尺寸 - 高效的数据存储
(远比的xml小)便宜了
方法 - 无论是在客户机和
服务器平台独立 - 便携式
不同的编程
架构之间扩展 - 新的
数据添加到旧邮件

small in size - efficient data storage (far smaller than xml) cheap to process - both at the client and server platform independent - portable between different programming architectures extensible - to add new data to old messages