What is the best way to create a network structure / class in C #?

I am wondering if there are good tutorials or books that explain the best way to handle network packet communication in C #?

I am currently using a structure and a method that generates a byte array based on the values ​​of the structure.

Is there an easier 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
        }
}

      

Other than that, is there a good tutorial or article on best practices for parsing network data in the structs / classes used?

+2


source to share


3 answers


Have you heard of Google Protocol Buffers ?



protocol buffers is the name of the binary serialization format used by Google for most of its communication data. It is intended for:

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

+2


source


Well, no GetBytes()

, I would be tempted to use Write(Stream)

if it's big ... but in general there are serialization APIs for that ... I would mention mine but I think people are bored of hearing this.



IMO, hotline_transaction

more like class

(than a struct

), btw.

+2


source


To do this, you should probably use BinaryWriter

, and not return byte[]

, you should pass BinaryWriter

in the serialization code, i.e.

public void WriteBytes(BinaryWriter writer)
{
    writer.Write((byte)0); // reserved
    writer.Write((byte)0); // request = 0

    writer.Write(Task_number);
    writer.Write(Transaction_id);
    writer.Write(error_code);

    writer.Write(Data_length);

    subBuffer.WriteBytes(writer);
}

      

You can easily wrap an existing one Stream

with BinaryWriter

. If you really need to get it somehow byte[]

, you can use it MemoryStream

as a fallback stream and call ToArray

when done.

0


source







All Articles