20181102_wcf simple duplex

Source: Internet
Author: User
  1. Use the Administrator permission to open vs2017

2. Create a blank solution:

3. Create several class library projects based on. NET Framework and a console Project Based on. NET Framework, and then delete the class1.cs file of the class library project, such:

4. Add the corresponding class file for each Class Library:

A) Add two interfaces to mywcf. wcfsimpleduplex. Interface: icalculatorservice and icallback. icalculatorservice indicates the service interface to be started, and icallback indicates the interface accessed when the client is to be called back.

B) The icalculatorservice code is as follows:

Using system. servicemodel; namespace mywcf. wcfsimpleduplex. interface {// <summary> // when defining the protocol, at the same time, you must define a callback interface // In the example, define a service contract, and define a callback interface icallback // functions in the duplex cannot return values. // if you really want to return values, then you can use out /// </Summary> [servicecontract (callbackcontract = typeof (icallback)] public interface icalculatorservice {/// <summary> /// to add the isoneway attribute, does this function return response information; /// </Summary> /// <Param name = "X"> </param> /// <Param name = "Y"> </param> [operationcontract (isoneway = true)] void plus (int x, int y); // establishes an icalculator service protocol // This Protocol has a callback interface icallback // pay attention to the WCF duplex, which cannot be configured by all, processing starts when a service is created }}

  

C) The icallback code is as follows:

Using system. servicemodel; namespace mywcf. wcfsimpleduplex. interface {// <summary> /// no protocol is required because it is not a service contract and is only a constraint, this constraint is implemented by the client // </Summary> Public interface icallback {// <summary> // This is the function completed during callback, isoneway = true // </Summary> /// <Param name = "M"> </param> /// <Param name = "N"> </param> /// <Param name = "result"> </param> [operationcontract (isoneway = true)] void show (int m, int N, int result);} // to publish a duplex protocol, you must first establish a WCF Service in the service, specify the callbackcontract callback type in the service contract. // create a callback interface. The callback interface is the interface to be executed}

  

5. Next we will process the code of mywcf. wcfsimpleduplex. model, which has a class:

using System.Runtime.Serialization;namespace MyWCF.WCFSimpleDuplex.Model{    [DataContract]    public class WCFUser    {        //[DataMember]        public int Id { get; set; }        [DataMember]        public int Age { get; set; }        [DataMember]        public int Sex { get; set; }        [DataMember]        public string Name { get; set; }        [DataMember]        public string Description { get; set; }    }    public enum WCFUserSex    {        Famale,        Male,        Other    }}

  

6. The processing of the service class mywcf. wcfsimpleduplex. service is as follows:

Using system. servicemodel; using mywcf. wcfsimpleduplex. interface; namespace mywcf. wcfsimpleduplex. service {/// <summary> /// an implementation class for icalculatorservice. To implement this class, you must complete your own calculations, call back the API // </Summary> public class calculatorservice: icalculatorservice {// <summary>, then go to the callback // </Summary> // <Param name = "X"> </param> // <Param name = "Y"> </param> public void plus (int x, int y) {int result = x + y; system. threading. thread. sleep (3000); // operationcontext indicates the context of the current operation // operationcontext. current. getcallbackchannel <icallback> (); here it is a bit like IOC. Give you an interface and generate an instance. Note that there is no implementation of icallback here, this implementation is completed at the client at icallback callback = operationcontext. current. getcallbackchannel <icallback> (); callback. show (X, Y, result );}}}

7. The following is the code implementation of mywcf. wcfsimpleduplex. consoletest in the console. The first is his configuration file.

A) The initial configuration file is as follows:

B) Add the following configuration on the configuration node:

 

<? XML version = "1.0" encoding = "UTF-8"?> <Configuration> <startup> <supportedruntime version = "v4.0" SKU = ". netframework, version = v4.5"/> </startup> <system. servicemodel> <! -- The WCF configuration file. One is TCP-based and the other is HTTP-based. You can add multiple; if you add multiple hosts, the following configuration format is used: <behaviors> <servicebehaviors> <! -- <Behavior name = "mathservicebehavior"> --> <! -- Configure the first behavior node here --> <! -- <Servicedebug enabled = "false"/> <servicemetadata httpgetenabled = "false"/> <servicetimeouts transactiontimeout = "00:10:00"/> <servicethrottling maxconcurrentcils = "1000" maxconcurrentinstances = "1000" maxconcurrentsessions = "1000"/> </behavior> --> <behavior name = "calculatorservicebehavior"> <! -- Configure the second behavior node here --> <servicedebug finished = "false"/> <servicemetadata httpgetenabled = "false"/> <servicetimeouts transactiontimeout = "00:10:00"/> <servicethrottling maxconcurrentcils = "1000" maxconcurrentinstances = "1000" maxconcurrentsessions = "1000"/> </behavior> </servicebehaviors> </behaviors> <! -- The configuration of the preceding lines in TCP is the same as that in HTTP --> <bindings> <nettcpbinding> <binding name = "tcpbinding"> <! -- Specify the TCP protocol type --> <security mode = "NONE"> <! -- Clientcredentialtype = "NONE" → indicates the encryption type protectionlevel = "NONE" indicates the security level --> <transport clientcredentialtype = "NONE" protectionlevel = "NONE"/> </Security> </ binding> </nettcpbinding> </bindings> <services> <service name = "mywcf. wcfsimpleduplex. service. calculatorservice "behaviorconfiguration =" calculatorservicebehavior "> 

C) The program code is as follows:

 

Using system; using system. servicemodel; using mywcf. wcfsimpleduplex. service; namespace mywcf. wcfsimpleduplex. consoletest {class program {static void main (string [] ARGs) {try {console. writeline ("starting to suspend service"); serviceinit. process ();} catch (exception ex) // if it is reported that it cannot be registered ..., the administrator privilege is required to start this program {// service "SOA. WCF. service. calculatorservice "has zero application (non-infrastructure) endpoints. This may be because the application configuration file is not found, the service element that matches the service name is not found in the configuration file, or the endpoint is not defined in the service element. // No configuration file // another application has registered the URL using HTTP. sys. // Port 9999 is occupied by other applications. Locate and stop the console. writeline (ex. message);} console. read () ;}/// <summary> // host the WCF to the console // </Summary> public class serviceinit {public static void process () {// servicehost → indicates the host that provides the service, and uses the service type and the specified base address to initialize the system. servicemodel. A new instance of the servicehost class. Type type = typeof (calculatorservice); servicehost host = new servicehost (type); host. opening + = (S, e) => console. writeline ($ "{type} is about to open"); // The Event Host has been opened. opened + = (S, e) => console. writeline ($ "{type} has been opened normally"); // enable the Service. Note that when open is required, check whether the behavior (behavior) Host of the mathservice class is configured in the configuration file. open (); console. writeline ("enter any character to stop"); console. read (); host. close (); console. read ();}}}

 

8. After completing the above steps, you can start and try again:

9. Run the CMD command netstat-ano | find "9999" to check whether port 9999 is listened.

 

10. The dual server has completed the processing, and then starts to process the client. Of course, the client must first implement the icallback just now, which is beyond doubt.

11. Open another vs2017 and create a console test project:

 

12. Next, you don't have to think about it. First, add service references. Second, implement the icallback interface of the server.

A) add service reference

 

B) implement the icallback interface. Note that the show method in this class is called without any code on the client.

 

Using system; namespace mywcf. wcfsimpleduplexconsoletest. ctest {/// <summary> /// specific implementation callback // </Summary> public class callbackservice: myduplexconsoletest. icalculatorservicecallback {public void show (int m, int N, int result) {console. writeline ($ "Callback operation display. This operation takes place two seconds later: {m} + {n }={ result }");}}}

  

C) Overall client:

 

13. Then the code in the program is recommended for One-Step debugging to see the code running process:

 

Using system; using system. servicemodel; namespace mywcf. wcfsimpleduplexconsoletest. ctest {class program {static void main (string [] ARGs) {myduplexconsoletest. calculatorserviceclient client = NULL; try {console. writeline ("client to test duplex! ~~ "); // Create an instance for callback. Wait for the server to call back the instancecontext context = new instancecontext (New callbackservice (); client = new myduplexconsoletest. calculatorserviceclient (context); client. plus (1, 123,234); client. close ();} catch (exception ex) {If (client! = NULL) client. Abort (); console. writeline (ex. Message) ;}console. Read ();}}}

14. Results

  

15. End

20181102_wcf simple duplex

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.