. Net platform, Socket communication protocol middleware design ideas (with source code), socket communication protocol

Source: Internet
Author: User

. Net platform, Socket communication protocol middleware design ideas (with source code), socket communication protocol

On the. net platform, there are many ways to implement communication processing (see the table below), each of which has its own advantages and disadvantages:

Serial number Implementation Method Features
1 WCF Advantages: good encapsulation and convenience. Disadvantages: hard to learn, not cross-platform
2 RocketMQ, SuperSocket, and other Middleware Advantages: lightweight disadvantages: fewer users
3 Use winsocket directly Advantage: all under your control, flexible protocols. Disadvantage: it takes a long time to implement and is prone to errors.

I have been developing socket communication for many years and have been working on "repeatedly inventing the wheel". This kind of work method is inefficient and error-prone!

If you have done a lot of repetitive things, there will also be a "Aura"! Why not design a set of middleware, and then design the application layer protocol. You can avoid repeating the wheel of invention ".

Source code: http://download.csdn.net/download/qq_29939347/10209713

First, the Protocol Stack:

This article describes how to design the green part.

The protocol design principles include:

Design Concept

The general principle is that classes on the. net platform are transmitted, rather than byte streams. Direct Processing of. net classes is much easier and safer than word throttling.

There are many types of. net platforms. I have extracted the most common ones, which are simple and meet the requirements of most application scenarios.

The following types can be transmitted: int, string, short, long, and byte;

And corresponding linked List types: List <int>, List <string>, List <short>, List <long>, byte [];

 

Total protocol package:

 

Public class NetPacket {public int PacketType {get; set ;}// package type public int Param1 {get; set ;}// parameter 1, public int Param2 {get; set;} // parameter 2 can be used according to the actual situation.
Public List <NetValuePair> Items {get; set ;}// List of transmitted key values
}

 

NetValuePair is defined as follows:
    public class NetValuePair    {        public string Key { get; set; }        public NetValueBase Value { get; set; }        public NetValuePair()        {        }    }

NetValueBase contains sub-types, corresponding to string, int, and so on. Take the string type as an example:

public class NetValueBase    {        public EN_DataType ValueType { get;protected set; }        public virtual object GetValue()        {            return null;        }    }

  

public class NetValueString: NetValueBase    {        public string Value { get; set; } = string.Empty;        public override object GetValue()        {            return Value;        }        public NetValueString()        {            ValueType = EN_DataType.en_string;        }        public NetValueString(string value)        {            ValueType = EN_DataType.en_string;            Value = value;        }    }
The NetValueString value must be transmitted as a byte stream and serialized as follows:
The string value is transmitted using utf8. First, the string is converted to the word throttling, and the length of the byte stream is written to the actual byte stream;
No extra fields are used in serialization. It is much more efficient than the serialization class processing that comes with. net. You can compare it.
 internal static void WriteStringValue(Stream stream, string value)        {            byte[] bytes = Encoding.UTF8.GetBytes(value);            WriteInt32(stream, bytes.Length);            stream.Write(bytes, 0, bytes.Length);        }

Serialization of other types is similar to this. How to perform deserialization is not hard to imagine.

Transmission

The serialized data needs to be sent and processed by the next layer.

The main function of this layer is subcontracting and contract. (Subcontracting is not required when data is small)

Public class RawNetPacket {public static int HeadLen = 14; public UInt16 PacketLen; public UInt32 PacketId; // the unique id of a complete package public UInt32 TotalNO; // The total number of packages public UInt32 PacketNO; // The package serial number public byte [] Body; // The data that carries the NetPacket serialization may be sent through subcontracting
}  

For details about how to subcontract and contract, refer to the source code of the attachment.

Example

1. transfer files

 

Private NetPacket GetPacketByFile (string fileName) {using (FileStream stream = new FileInfo (fileName ). openRead () {NetPacket result = new NetPacket (); result. packetType = 2; result. param1 = 2; result. param2 = 3; result. items = new List <NetValuePair> (); // string NetValuePair pair = new NetValuePair (); pair. key = "file name"; pair. value = new NetValueString (fileName); result. items. add (pair); // byte pair = new NetValuePair (); pair. key = "file binary data"; NetValueListByte fileBuffer = new NetValueListByte (); fileBuffer. value = new byte [stream. length]; stream. read (fileBuffer. value, 0, Convert. toInt32 (stream. length); pair. value = fileBuffer; result. items. add (pair); return result ;}}

 

2 Transfer object

The object can be serialized as a json string and then transmitted.

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.