Join me in learning WCF (9) -- Implementation of the WCF callback operation and the wcf callback
I. Introduction
In the previous article, we introduced the Session support for WCF. In this article, we will detail the operations supported by WCF. In WCF, in addition to the classic request/response mode, it also supports unidirectional operations and bidirectional callback operation modes, as well as stream operations. The following describes these operations in detail and provides an example of a two-way callback operation.
Ii. Explanation of WCF operations 2.1 request-response operations
The request response mode is the default operation mode in WCF. The request response mode indicates that the client sends a request in the form of a message, which blocks the client until it receives the Response Message. The default response timeout is 1 minute. If the service still does not respond after this time, the client will get a TimeOutException exception. In WCF, except for binding NetPeerTcpBinding and NetMsmqBinding, all bindings support request-response operations.
2.2 unidirectional operations
One-way operations do not return values, and the client does not care whether the call is successful or not. One-way operation means that once the client sends a call request, WCF generates a request message and sends it to the server. However, the client does not need to receive the relevant response message. Therefore, one-way operations cannot return values, and any exceptions thrown by the server will not be passed to the client. Therefore, if the client needs to capture exceptions on the server, the IsOneWay attribute of the operation contract cannot be set to true, and the default value of this attribute is false. Exception Handling reference: how to perform Exception Handling in WCF. One-way operations are not the same as asynchronous operations. One-way operations only block the client when a call is made. However, if multiple one-way calls are made, WCF puts the request call in the queue of the server, and execute it at a certain time. The number of queues is limited. Once the number of calls exceeds the queue capacity, blocking occurs. At this time, the call request cannot be placed in Ding lie until other requests are processed, that is, after a request in the queue is sent out of the queue, the call that produces blocking will be put into the queue and the blocking on the client will be removed. All bindings in WCF support one-way operations. To implement one-way operations in WCF, you only need to set the IsOneWay attribute to true. Note that a one-way operation does not respond to a message, so it cannot contain the returned result.
2.3 callback operation
The WCF support service returns a call to its client. During the callback, the service becomes a client, and the client becomes a service. In WCF, not all bindings support callback. Only bindings with Bidirectional capabilities can be used for callback. For example, HTTP is essentially unrelated to the connection, so it cannot be used for callback. Therefore, we cannot use callback based on basicHttpBinding and wsHttpBinding binding. WCF provides callback support for NetTcpBinding and NetNamedPipeBinding, because both TCP and IPC protocols support two-way communication. To enable Http to support callback, WCF provides WsDualHttpBinding binding. It actually sets two Http channels: one for calling from the client to the service, and the other for calling from the service to the client.
Callback is implemented through a callback contract. A callback contract is part of a service contract. A service contract can only contain One callback contract. Once the callback contract is defined, the client needs to implement the callback contract. In WCF, The CallbackContract attribute of ServiceContract can be used to define the callback contract. The specific implementation code is as follows:
// Specify the callback contract as ICallback [ServiceContract (Namespace = "http://cnblog.com/zhili/", CallbackContract = typeof (ICallback)] public interface ICalculator {[OperationContract (IsOneWay = true)] void Multiple (double a, double B);} // callback contract definition. In this case, the callback contract does not need to apply the ServiceContractAttribute attribute public interface ICallback {[OperationContract (IsOneWay = true)] void DisplayResult (double x, double y, double result );}
In the above Code, the callback contract does not need to mark ServiceContract. As long as the type is defined as a callback contract, it indicates that it has ServiceContract, however, OperationContract must be marked for all methods in the callback interface.
2.4 stream operations
By default, when the client exchanges messages with the service, these messages are placed in the cache of the acceptor. Once a complete message is received, the messages are immediately transmitted for processing. This is true for clients that send messages to the service or services that return messages to the client. When the client calls the service, the service will be called as long as it receives the complete message. When the return message containing the call result is received by the client completely, to block the client. For messages with a small amount of data, this exchange mode provides a simple programming model because it takes a short time to receive messages. However, once a message with a larger data volume is processed, for example, if a file contains multimedia content or large files, it cannot be blocked until the message is received completely. To solve this problem, WCF allows the receiving end to start processing the message data while receiving messages through the channel. Such a process is called a stream transmission model. For messages with a large load, stream Operations improve the system throughput and response speed, because both the sender and the receiver are not blocked when messages are received.
Iii. Implementation of callback operations in WCF
The above describes four types of operations supported by WCF. The following describes the implementation of callback operations in WCF. The basic principle of this example is: the client calls service operations, and service operations call client operations through the client context instance. Follow the three steps below to implement the WCF program.
Step 1: implement the WCF Service Contract and contract. The specific implementation code is as follows:
1 // specify the callback contract as ICallback 2 [ServiceContract (Namespace = "http://cnblog.com/zhili/", CallbackContract = typeof (ICallback)] 3 public interface ICalculator 4 {5 [OperationContract (IsOneWay = true)] 6 void Multiple (double a, double B); 7} 8 9 // callback contract definition, in this case, the callback contract does not need to apply the ServiceContractAttribute feature 10 public interface ICallback11 {12 [OperationContract (IsOneWay = true)] 13 void DisplayResult (double x, double y, double result ); 14} 15 16 // service contract implementation 17 public class CalculatorService: ICalculator18 {19 # region ICalculator Members20 public void Multiple (double a, double B) 21 {22 double result = a * B; 23 // use the client instance Channel 24 ICallback callback = OperationContext. current. getCallbackChannel <ICallback> (); 25 26 // calls back the client operation 27 callback. displayResult (a, B, result); 28} 29 # endregion30}
Step 2: implement the service host. The console program is used as the service host. The specific implementation code is as follows:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 using (ServiceHost host = new ServiceHost(typeof(CalculatorService))) 6 { 7 host.Opened += delegate 8 { 9 Console.WriteLine("Service start now....");10 };11 12 host.Open();13 Console.Read();14 }15 }16 }
The content of the configuration file corresponding to the host is as follows:
<configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8080/Metadata"/> </behavior> </serviceBehaviors> </behaviors> <services> <service name="WCFContractAndService.CalculatorService"> <endpoint address="net.tcp://localhost:9003/CalculatorService" binding="netTcpBinding" contract="WCFContractAndService.ICalculator"/> </service> </services> </system.serviceModel></configuration>
Step 3: implement the client. Because the server calls back the client operations, the client needs to implement the callback contract. First, start the service host as an administrator. After the service host is started successfully, the client generates a client proxy class by adding a service reference. In this case, enter http: // localhost: 8080/Metadata. After the service reference is successfully added, implement the callback contract on the client. The specific implementation code is as follows:
1 // Implementation of the callback contract in the Client 2 public class CallbackWCFService: ICalculatorCallback3 {4 public void DisplayResult (double a, double B, double result) 5 {6 Console. writeLine ("{0} * {1} = {2}", a, B, result); 7} 8}
The next step is the client code that implements the test callback operation. The specific implementation steps are as follows: instantiate a callback class instance and use it as the context instance operation. Finally, the context instance is used as the client proxy parameter to instantiate the client proxy. The specific implementation code is as follows:
1 // client implementation, test callback operation 2 class Program 3 {4 static void Main (string [] args) 5 {6 InstanceContext instanceContex = new InstanceContext (new CallbackWCFService ()); 7 CalculatorClient proxy = new CalculatorClient (instanceContex); 8 proxy. multiple (2, 3); 9 10 Console. read (); 11} 12}
Run the program below to check whether the program can be successfully called back. First, start the service host Program with the administrator privilege and then start the client program. If the callback succeeds, you will see the running result as shown in:
All source code in this article: WCFCallbackOperation.zip
C # after the client registers with the wcf Service, the wcf receives the data and delivers the data to all registered clients. Let's talk about it!
The wcf Service defines a State (attribute ),
Update this status after registration
The client periodically checks the status on the server.
Ask a question about wcf Duplex Communication
1. on the service contract, mark which callback contract you use.
[ServiceContract (CallbackContract = typeof (your callback contract type)]
Second, the callback contract is used by the server to control the client. For example, a typical scenario is that the client returns results immediately after the request is submitted, and the server notifies the client of the results after processing for a period of time.
Third: "If I have a general console and want to control the following clients, do I have to use the wcf duplex Technology for implementation ?" Yes.
Fourth: "What technology should I use for QQ remote operations?" is complicated. In short, the operator sends an instruction to the receiver, which operates according to the instruction and returns the image data. For example, when an operator sends the mouse and keyboard information, the receiver converts the information into a Windows message and sends it to the Operating System (equivalent to recreating a mouse and keyboard operation ).