WCF Transport 1-have you used compression or JSON serialization?

Source: Internet
Author: User
Tags asymmetric encryption

1. How do I transfer data when I encounter the need to transfer large amounts of data?

2. What are some common ways to compress data?

Question 1 Answer: transfer data by compression

Question 2 Answer:

(1) The compression method of the WCF comes with

(2) Custom WCF binding for compression

(3) Serializing objects into JSON format

Today, let's explore the compression method of WCF's own gzip and JSON serialization

My other WCF articles:

WCF Security 1-opening

WCF Security 2-Asymmetric encryption

WCF security 3-transport and message Safe mode

WCF Transport 1-have you used compression or JSON serialization?


1.WCF of compression to compress data and transfer data

Reference: Https://msdn.microsoft.com/en-us/library/system.servicemodel.channels.compressionformat.aspx

There are a total of three ways:
Deflate: The Deflate compression format.
GZip: The GZIP compression format.
None: The none compression format.

Note that the. NET framwork version needs to be above 4.0 (contains 4.0).

The implementation of 1.1 code:

(1) Configuration of server side and client

< Code class= "HTML keyword" >binarymessageencoding  compressionformat= "GZip"

 <bindings> <custombinding  > <binding name= "bindingfortcp " receivetimeout= "00:05:00" sendtimeout= " 00:05:00 "> <binarymessageencoding   Compre ssionformat= "GZip"   > <readerquotas maxstringcontentlength= "2147483647" maxarraylength= "2 147483647 "maxbytesperread=" 2147483647 "/> </binaryMessageEncoding> 
<services>      <service name= "Jackson0714.WcfServices.Service.GetPersonDetailService"               behaviorconfiguration= "Metadatabehavior" >        <endpoint address= " Getpersondetailservice "                  binding="custombinding"                   bindingconfiguration =" Bindingfortcp "                  contract= "Jackson0714.WcfServices.Service.Interface.IGetPersonDetailService"/>      </service> </services>

Note: The client and server side must use the same binding.

(2) server-side code

Open port, Host service

Using system;using system.servicemodel;using Jackson0714.wcfservices.service;namespace jackson0714.wcfservices.hosting{    class program    {        static void Main (string[] args)        {            ServiceHost Getpersondetailservicehost = null;            Try            {                getpersondetailservicehost = new ServiceHost (typeof (Getpersondetailservice));                Getpersondetailservicehost.open ();                Console.WriteLine ("Getpersondetailservice started! ");                Console.readkey ();            }            catch (Exception ex)            {                Console.WriteLine (ex. StackTrace);            }            Finally            {                getpersondetailservicehost.close ();            }        }}}    

(3) client-side code

Calling Methods Getpersondetail

Using system;using system.servicemodel;using Jackson0714.wcfservices.service.interface;namespace jackson0714.wcfservices.client{    class program    {        static void Main (string[] args)        {            using ( channelfactory<igetpersondetailservice> ChannelFactory = new Channelfactory<igetpersondetailservice> (" Getpersondetailservice "))            {                Igetpersondetailservice proxy = Channelfactory.createchannel ();                Console.WriteLine ("Person decription:{0}", Proxy. Getpersondetail ("123"). Description);            }            Console.read ();}}}    

(4) interface

Using jackson0714.wcfservices.common;using system.servicemodel;namespace jackson0714.wcfservices.service.interface{    [ServiceContract (Name = "Getpersondetailservice", Namespace = "http ://www. jackson0714.com/")] public    interface Igetpersondetailservice    {        [operationcontract]        person Getpersondetail (string name);}    }

(5) Implement the interface method

Using jackson0714.wcfservices.common;using jackson0714.wcfservices.service.interface;namespace jackson0714.wcfservices.service{public    class Getpersondetailservice:igetpersondetailservice    {        Public person Getpersondetail (string name)        {person person            = Dataaccess.mockquerypersondetail (name);            return person;}}    }

(6) Mock database access layer


The data size of the description that simulates the person class is 100000 bytes

Using jackson0714.wcfservices.common;using system.text;namespace jackson0714.wcfservices.service{    class DataAccess    {public        static person Mockquerypersondetail (string name)        {person person             = new person ();            Person. Name = "Jackson0714";            String teststring = "0123456789";            StringBuilder builder = new StringBuilder ();            for (Long i = 0;i<10000;i++)            {                Builder. Append (teststring);            }            Person. Description = Builder. ToString ();            return person;}}    }

(6) Person class

namespace jackson0714.wcfservices.common{public    class person    {        private string name;        public string Name        {            get            {                return this.name;            }            Set            {                name = value;            }        }        private string description;        public string Description        {            get            {                return this.description;            }            Set            {                description = value;            }        }}}    

1.2 Analysis Results

By Wireshare grasping the packet, you can get the total size of the whole session to 25451 bytes (because some data is lost when grabbing the packet, so the packet size is less than 100000 bytes far)

After compression, the total size of the session 1071 bytes, which is much smaller than the amount of uncompressed data.

1.3 Print Window

2. Transfer using JSON-formatted data

The server side first serializes the data into JSON-formatted data, the string type, and the client side receives the JSON-formatted data and deserializes it into JSON-formatted data.

Need to introduce Newtonsoft.Json.dll

: Http://www.newtonsoft.com/json

The implementation of 2.1 code:

(1) Defining the interface

Using jackson0714.wcfservices.common;using system.servicemodel;namespace jackson0714.wcfservices.service.interface{    [ServiceContract (Name = "Getpersondetailservice", Namespace = "http ://www. jackson0714.com/")] public    interface Igetpersondetailservice    {        [OperationContract]        string Getpersondetailwithjson (string name);}    }

(2) Implement the interface


Use jsonconvert.serializeobject (person) to serialize a person into JSON-formatted data.

public string Getpersondetailwithjson (string name) {person person     = Dataaccess.mockquerypersondetail (name);     Jsonconvert.serializeobject (person);}

(3) Client call Getpersondetailwithjson

Use Jsonconvert.deserializeobject<person> (proxy. The Getpersondetailwithjson ("123")) method deserializes data in JSON format and converts the data in JSON format into a person object.

using (channelfactory<igetpersondetailservice> ChannelFactory = new Channelfactory<igetpersondetailservice > ("Getpersondetailservice") {      Igetpersondetailservice proxy = Channelfactory.createchannel ();      jsonconvert.deserializeobject<person> (proxy. Getpersondetailwithjson ("123"));      Console.WriteLine ("Getpersondetailwithjson->person decription:{0}", person. Description); }
2.2 Analysis Results

The following figure shows that the data transfer size for the entire session is 42878 bytes, which reduces 50%.

Here's a question, why is the data in JSON format smaller than the original WCF-based XML-transmitted data???

The reason is that the data transmitted by WCF is serialized as XML and requires many tags to record the contents of each field. In JSON format, data has been converted into key-value pairs of data, without labels, so the amount of data is much reduced.

2.3 Print Window

3. The implementation of 3.1 code transmission via json+ compression

(1) Defining the WCF compression method

<binarymessageencoding compressionformat= "GZip" >

(2) Serializing objects into JSON-formatted data

Jsonconvert.serializeobject (person);

(3) Deserializing data in JSON format into objects

Person person = jsonconvert.deserializeobject<person> (proxy. Getpersondetailwithjson ("123"));
3.2 Analysis Results

It can be seen that JSON-formatted and then compressed data is 1004 bytes, and the data that is not formatted with JSON is 1071 bytes, reducing 67 bytes.


4. What do I need to be aware of by compressing or json formatting?

(1) Compression or JSON formatting requires a certain amount of resources, if the CPU and memory is low, be careful to use compression or JSON format.

(2) Compression or JSON formatting takes a certain amount of time, if the volume of data is very large, then the compression or JSON format time is also very large, for the need to quickly respond to the system, with caution in compression or JSON format.

WCF Transport 1-have you used compression or JSON serialization?

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.