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

Source: Internet
Author: User
Tags asymmetric encryption

Read Catalogue

    • 1.WCF of compression to compress data and transfer data
    • 2. Transfer using JSON-formatted data
    • 3. Transfer via json+ compression
    • 4. What do I need to be aware of by compressing or json formatting?
    • 5. References

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?

First:

Back to top of 1. Compressed data and transfer data with WCF's own compression method

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

<binarymessageencodingcompressionformat="GZip">

123456789101112 <bindings>  <custombinding>    <bindingname="BindingForTcp" receivetimeout="00:05:00" sendtimeout="00:05:00">        <binarymessageencodingcompressionformat="GZip">          <readerquotasmaxstringcontentlength="2147483647" maxarraylength="2147483647" maxbytesperread="2147483647"></readerquotas>        </binarymessageencoding>        <httptransportmaxreceivedmessagesize="2147483647">                  </httptransport>      </binding>    </custombinding></bindings>
12345 <services>      <servicename="Jackson0714.WcfServices.Service.GetPersonDetailService" behaviorconfiguration="metadataBehavior">        <endpointaddress="http://127.0.0.1:3725/GetPersonDetailService" binding="customBinding" bindingconfiguration="BindingForTcp" contract="Jackson0714.WcfServices.Service.Interface.IGetPersonDetailService"></endpoint>      </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

Getpersondetail
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

Getpersondetail
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

Mockquerypersondetail

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

Person
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

Through Wireshare grasping packet, can know response data size is content-length:100352 bytes.

After compression, the data size of the response is content-length:506 bytes. , which is much smaller than the amount of uncompressed data.

1.3 Print Window

Back to top 2. Using JSON-formatted data for transmission

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

Getpersondetailwithjson
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

Getpersondetailwithjson

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

public string Getpersondetailwithjson (string name) {person person     = Dataaccess.mockquerypersondetail (name);     return 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 ChannelFactory = new ChannelFactory ("Getpersondetailservice")) {      Igetpersondetailservice Proxy = Channelfactory.createchannel ();      Person person = jsonconvert.deserializeobject (proxy. Getpersondetailwithjson ("123"));      Console.WriteLine ("Getpersondetailwithjson->person decription:{0}", person. Description); }
2.2 Analysis Results

By Wireshare grasping the packet, you can know the response data size is content-length:100263bytes. Bytes data is reduced by more than the data that has not been serialized.

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 reduced.

2.3 Print Window

Back to top 3. Transmission of 3.1 code by json+ compression

(1) Defining the WCF compression method

1 <binaryMessageEncodingcompressionFormat="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.

 

Back to top 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.

Back to top 5. Resources

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

https://msdn.microsoft.com/en-us/library/ms751458 (v=vs.110). aspx

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?


Author: Jackson0714
Source: http://www.cnblogs.com/jackson0714/
About project development that focuses on Microsoft platforms. If you have any questions or suggestions, please enlighten me!
Copyright NOTICE: This article is copyright to the author and the blog Park is shared, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to give the original link.
It is hereby stated that all comments and private messages will be answered at the first time. Also welcome the garden of the big to correct mistakes, common progress. or direct messages to me.
Supporters: If you feel that the article is helpful, you can click "recommend" in the lower right corner of the article. Your encouragement is the ultimate motivation for the author to insist on original and continuous writing!

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

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.