The exploration of socket development--data protocol transceiver based on JSON format

Source: Internet
Author: User
Tags foreach json reflection socket

Previously published two essays: "Socket Development Quest--the definition of basic class and public class" and "Socket Development quest-Data packet and unpacking", introduced the development of socket. This article continues to explore the technical aspects of using the JSON format as a socket transceiver protocol.

Before, the received socket data after a rough parsing, is the predata type of data, this is a general data format, we need to further processing to be able to understand the data object (Entity class object), the same, we send data, The content is definitely in line with a certain protocol rules, then we need to transform the entity into a sent data format. To sum up, through the entity class, we must implement the data send and read conversion.

Because the packet unpacking of the data is a tedious process, the code is more repetitive and error prone. As described earlier in the design of a base class, we put all the data on the unpacking and encapsulation, using reflection mechanism, reduce our code volume, improve the elegance of the code. But it was later suggested that the possible use of JSON-formatted data content might be better, and indeed, if the content of the split symbol is used, there is a disadvantage that the data content is more difficult to understand (sometimes we still need to analyze the packet), and JSON is easier to read. In addition, using JSON can be separated from the order of the fields and can be backwards compatible with some historical protocols, such as the first defined protocol has fields a, B, later the server upgrades, upgrades support C, D, the old client can coexist with the new client, increased compatibility.

So I optimize the code on this basis, so that it supports the JSON format of the data sent, in fact, because the previous code encapsulation is relatively good, so modify the content of the protocol in JSON format, only need to modify a few lines of baseentity code can be achieved, Here's a comparison of the changes to the code (the Annotated code is the original code):

public class BaseEntity


     {


protected string Headerkey;


public baseentity ()


         {


         }


///<summary>


Convert socket received information as object information


///</summary>


///<param name= "Data" >socket received information </param>


public baseentity (string data)


         {


#region Normal, sequentially constructed code


//string[] DataArray = null;


//dataarray = netstringutil.unpack (data);


//if (dataarray!= null && dataarray.length > 0)


             //{


//int i = 0;


//fieldinfo[] Fieldarray = Reflectionutil.getfields (this);


//if (Fieldarray = null | | | Dataarray.length!= fieldarray.length)


             //    {


//throw new ArgumentException ("Inconsistent information received and field information");


             //    }


if (Fieldarray!= null)


             //    {


//foreach (FieldInfo info in Fieldarray)


             //        {


//String strvalue = dataarray[i++];


//Reflectionutil.setfield (this, info. Name, strvalue);


             //        }


             //    }


             //}


#endregion

The contents of the
//json format conversion must be less than or equal to the contents of the entity class


//Because the object is to be compatible with the historical JSON content, by reflection with the smallest member to assign the value


baseentity obj = jsontools.jsontoobject (data, this. GetType ()) as baseentity;


if (obj!= null)


             {


fieldinfo[] Fieldarray = reflectionutil.getfields (obj);


foreach (FieldInfo info in Fieldarray)


                 {


Object value = Reflectionutil.getfield (obj, info. Name);


Reflectionutil.setfield (this, info.) Name, value);


                 }


             }


         }


///<summary>


///Converts a string to the socket format


///</summary>


///<returns></returns>


public override string ToString ()


         {


String data = "";


#region Normal, sequentially constructed code


//fieldinfo[] Fieldarray = Reflectionutil.getfields (this);


//stringbuilder sb = new StringBuilder ();


//if (fieldarray!= null)


             //{


foreach (FieldInfo info in Fieldarray)


             //    {


//SB. Append (this, info, Reflectionutil.getfield. Name));


//SB. Append ("|");


             //    }


             //}


//data = sb. ToString (). Trim (' | ');


#endregion


#region code constructed in JSON format


data = Jsontools.objecttojson (this);


#endregion





if (string. IsNullOrEmpty (Headerkey))


             {


throw new ArgumentNullException ("Datatypekey", "entity class does not specify protocol type");


             }


data = Netstringutil.packsend (Headerkey, data);


return data;


         }


     }

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.