Legendary WCF (8): Play with message protocols

Source: Internet
Author: User
The legendary WCF (1): Is this hard to learn?The legendary WCF (2): What about service agreements?Legendary WCF (3): multiple protocolsLegendary WCF (4): send and receive SOAP HeadersLegendary WCF (5): data protocols ()Legendary WCF (6): data protocols (B)Legendary WCF (7): "one-way" & "two-way"Legendary WCF (8): Play with message protocolsLegendary WCF (9): stream and file transferLegendary WCF (10): message interception and tamperingThe legendary WCF (11): Session)The legendary WCF (12): What is the use of server callback?Legendary WCF (13): group chat programThe legendary WCF (14): WCF can also be used as a chat program.

 

 

The message is translated into Chinese. I believe you are familiar with it. Yes, it is a message. There is also a message in WCF, and you do not know how to understand it. What I understand is like sending text messages to each other. The communication between the two parties is the communication between the server and the client. To put it bluntly, it is the communication between the two.

We know that a WCF Service first defines a service agreement, and a service agreement contains several service operation agreements (operationcontract), right? The so-called operational agreement is a method.

As a result, I have come to the conclusion that the client communicates with the server. Each call to an operation agreement is equivalent to sending/receiving a message. You can simply understand it as an operationcontract as a message, this should be acceptable.

In the previous article, we blew the technology related to modifying the SOAP header, and the message we are going to talk about today is actually serialized as soap, which is related to soap anyway. Maybe you will ask, if I do not understand the specific knowledge of soap, will it be difficult for me to use message? Tell you clearly. No, you can see the examples I have prepared for you below. We can also play message without understanding soap, it's like we don't know how to plant rice, but it also makes sense to cook.

Message protocols allow us to more flexibly encapsulate custom messages. Since we can regard a call to an operational agreement as a message, the following three situations may occur:

A: Only receive messages, but do not answer them;

B: Only replies to messages and does not receive input messages;

C: if there is a loan, it is not difficult to borrow it again. It receives the input message and sends the reply message at the same time.

 

First, define the required Message Protocol class.

[Messagecontract]
Public class carmessage
{
[Messagebodymember]
Public String carname;
[Messagebodymember]
Public int makeyear;
[Messagebodymember]
Public String sertype;
}

[Messagecontract]
Public class person
{
[Messageheader]
Public String zip {Get; set ;}
[Messageheader]
Public String address;

[Messagebodymember]
Public int age {Get; set ;}
[Messagebodymember]
Public string name {Get; set ;}
[Messagebodymember]
Public String email {Get; set ;}
}

# Region Input/Output Message Protocol
[Messagecontract]
Public class requrestmessage
{
[Messageheader]
Public int maxnum;
[Messagebodymember]
Public String checkname;
}

[Messagecontract]
Public class responsemessage
{
[Messagebodymember]
Public string name;
[Messagebodymember]
Public int checkresult;
}
# Endregion

We can see that the definition of a message protocol is similar to that of a data protocol. We also write a class first and then append messagecontractattribute. For the class members (fields or attributes, whether public or private) you can append messageheaderattribute or messagebodymemberattribute.

In fact, messageheaderattribute and messagebodymemberattribute are not fundamentally different. They are only the message header and the message body, which is only for soap messages.

 

Next, define the service agreement and server class.

[Servicecontract]
Public interface iservice
{
[Operationcontract]
Void postmessage (carmessage MSG );

[Operationcontract]
Person getperson ();

[Operationcontract]
Responsemessage checkrenpin (requrestmessage rqmsg );
}

Public class myservice: iservice
{
Public void postmessage (carmessage MSG)
{
Console. writeline ("car name: {0}", MSG. carname );
}

Public Person getperson ()
{
Person PS = new person ();
PS. Name = "Birdman ";
PS. Age = 107;
PS. Email = "nb@niube.com ";
PS. Zip = "990 ";
PS. Address = "Africa ";
Return pS;
}

Public responsemessage checkrenpin (requrestmessage rqmsg)
{
Responsemessage respmsg = new responsemessage ();
Random Rand = new random ();
Respmsg. checkresult = Rand. Next (rqmsg. maxnum );
Respmsg. Name = rqmsg. checkname;
Return respmsg;
}
}

 

The rest is some settings for the service host, which is the same every time.

Static void main (string [] ARGs)
{
// Server base address
Uri baseaddress = new uri ("http: // localhost: 1378/services ");
// Declare the server host
Using (servicehost host = new servicehost (typeof (myservice), baseaddress ))
{
// Add binding and endpoints
Wshttpbinding binding = new wshttpbinding ();
Host. addserviceendpoint (typeof (iservice), binding, "/test ");
// Add service description
Host. description. behaviors. Add (New servicemetadatabehavior {httpgetenabled = true });
Try
{
// Open the service
Host. open ();
Console. writeline ("service started. ");
}
Catch (exception ex)
{
Console. writeline (ex. Message );
}
Console. readkey ();
}
}

After confirming that the server runs normally, add a service reference on the client.
In the proxy class generated by the client, the Message Protocol and Data Protocol are not the same. The service operation protocol is different from what we define on the server.


 

We can see that the Message Protocol class defined on the server side is split in the client code. This leads to the following conclusion:

The input Message Protocol (as a parameter) encapsulates all in parameters of the operation method, and the return value of the operation protocol encapsulates the out parameters and return values.

 

Next, let's take a look at the example of message protocols that contain data protocols.

# Region message Protocols containing data protocols
[Datacontract]
Public class artistinfo
{
[Datamember]
Public String artistname;
[Datamember]
Public datetime createtime;
}

[Messagecontract]
Public class worker
{
[Messageheader]
Public artistinfo workerartist;
[Messagebodymember]
Public String workername;
[Messagebodymember]
Public String workerno;
[Messagebodymember]
Public int workerage;
}
# Endregion

 

The Message Protocol Class is worker, but the workerartist field of worker is a data protocol class artistinfo.

Then we add a method to the service agreement.

[Servicecontract]
Public interface iservice
{
........
[Operationcontract]
Void setworkerinformation (worker WK );
}

 

Public class myservice: iservice
{
.............
Public void setworkerinformation (worker WK)
{
Console. writeline ("working name: {0}", wk. workername );
Artistinfo info = wk. workerartist;
Console. writeline ("worker Creation Time: {0}", info. createtime. tostring ("yyyy-mm-dd hh: mm: SS "));
Console. writeline ("worker name: {0}", info. artistname );
}
}

 

Now, test the setworkerinformation method on the client.

Static void main (string [] ARGs)
{
WS. serviceclient Cl = new ws. serviceclient ();

WS. artistinfo info = new ws. artistinfo
{
Artistname = "Advanced junk ",
Createtime = new datetime (2018, 7, 17)
};
Cl. setworkerinformation (Info, 180, "Old demon", "NB-117 ");

Console. readkey ();
}

Because the method returns void, the console window is blank after the customer calls the method. We mainly observe whether the console window on the server outputs relevant content.

This indicates that the call is successful.

Let's take a look at the time when message protocols are used. We don't have to hesitate to use them. This is obviously better than the message class. After all, the message class also has some inexplicable bugs, I don't know if it's my bug. It is a good choice to use message protocols for encapsulation in stream transmission mode.

For the message body of the message header, there is no strict rule. Do not believe it. The general principle is that, similar to additional information, it can be used as the header and important information as the body. Try again. No matter whether your member is defined as the header or the body, there is no fundamental difference in code calling.

 

 

 

Turn to it

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.