代码下载:http://files.cnblogs.com/AlwinXu/CallbackService-master.zip

本文转自:

http://adamprescott.net/2012/08/15/a-simple-wcf-service-callback-example/

A Simple WCF Service Callback Example

11 Replies

I’ve done a lot with WCF services over the past few years, but I haven’t done much with callbacks. I wanted to write a simple application to understand and demonstrate how a callback service works in WCF. The example described below was implemented in a single solution with two console application projects, one client and one server.

Create the server

The first thing we’ll do is create and host our WCF service. This will be done in five short steps:

  1. Create      the service contract
  2. Create      the service callback contract
  3. Create      the service implementation
  4. Modify      the endpoint configuration
  5. Host      the service

To create the service contract, service implementation, and default endpoint configuration, you can use Visual Studio’s menu to choose Add New Item > Visual C# Items > WCF Service. I named my service MyService, and so my service contract is called IMyService. Visual Studio creates the service contract with a single method, DoWork. I decided that I wanted my service to have two methods: OpenSession and InvokeCallbackOpenSession will be used by the server to store a copy of the callback instance, and InvokeCallback will be used to trigger a callback call to the client from the client.

Here’s my complete IMyService contract:

1

2

3

4

5

6

7

8

9

10

11

using System.ServiceModel;

namespace CallbackService.Server

{

    [ServiceContract(CallbackContract   = typeof(IMyServiceCallback))]

    public interface IMyService

    {

        [OperationContract]

        void OpenSession();

    }

}

Note that the service contract indicates the callback contract in its attribute. The callback contract, IMyServiceCallback, will have a single method, OnCallback. Here is the complete IMyServiceCallback interface:

1

2

3

4

5

6

7

8

9

10

using System.ServiceModel;

namespace CallbackService.Server

{

    public interface IMyServiceCallback

    {

        [OperationContract]

        void OnCallback();

    }

}

The third step requires us to implement our service. When OpenSession is called, I create a timer that will invoke the callback once per second. Note the ServiceBehavior attribute that sets the ConcurrencyMode to Reentrant. If you do not change the ConcurrencyMode to Multiple or Reentrant, the channel will be locked and the callback will not be able to be invoked. Here is the complete MyService implementation:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

using System;

using System.ServiceModel;

using System.Timers;

namespace CallbackService.Server

{

    [ServiceBehavior(ConcurrencyMode   = ConcurrencyMode.Reentrant)]

    public class MyService   : IMyService

    {

        public static IMyServiceCallback   Callback;

        public static Timer   Timer;

        public void OpenSession()

        {

            Console.WriteLine(">   Session opened at {0}", DateTime.Now);

            Callback   = OperationContext.Current.GetCallbackChannel<IMyServiceCallback>();

            Timer   = new Timer(1000);

            Timer.Elapsed   += OnTimerElapsed;

            Timer.Enabled   = true;

        }

        void OnTimerElapsed(object sender,   ElapsedEventArgs e)

        {

            Callback.OnCallback();

        }

    }

}

When we added the new WCF service to the project, Visual Studio added the default endpoint configuration to the app.config. By default, wsHttpBinding is used as the binding. We want to change it to use wsDualHttpBinding which supports two-way communication. I also changed the URL to be friendlier, but that is not necessary. Here’s my final app.config:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <system.serviceModel>

    <behaviors>

      <serviceBehaviors>

        <behavior name="">

          <serviceMetadata httpGetEnabled="true" />

          <serviceDebug includeExceptionDetailInFaults="false" />

        </behavior>

      </serviceBehaviors>

    </behaviors>

    <services>

      <service name="CallbackService.Server.MyService">

        <endpoint address="" binding="wsDualHttpBinding" contract="CallbackService.Server.IMyService">

          <identity>

            <dns value="localhost" />

          </identity>

        </endpoint>

        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

        <host>

          <baseAddresses>

            <add baseAddress="http://localhost:8090/CallbackService.Server/MyService/" />

          </baseAddresses>

        </host>

      </service>

    </services>

  </system.serviceModel>

</configuration>

The final step is to simply host the service. Since my server is a console application, I do this in the Program.Main method. Here is the complete class:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

using System;

using System.ServiceModel;

namespace CallbackService.Server

{

    class Program

    {

        static void Main(string[]   args)

        {

            var host   = new ServiceHost(typeof(MyService));

            host.Open();

            Console.WriteLine("Service   started at {0}", DateTime.Now);

            Console.WriteLine("Press   key to stop the service.");

            Console.ReadLine();

            host.Close();

        }

    }

}

Create the client

With the server complete, creating the client is a breeze. We’ll complete the client in just three steps:

  1. Add      a service reference
  2. Implement      the callback class
  3. Create      the client proxy

To add the service reference, you must have the service running. I did this by simply running the server executable outside of Visual Studio. You can copy the URL from the server’s app.config. Right-click References in your client project, choose Add Service Reference, and paste the URL. I named my service reference MyServiceReference.

The service reference pulls in IMyServiceCallback, which will allow us to create our callback class. To do this, just add a new, empty class to the project. I named my class MyServiceCallback, and when the callback is invoked, it just writes a line to the console. Here is the complete implementation:

1

2

3

4

5

6

7

8

9

10

11

12

13

using System;

using CallbackService.Client.MyServiceReference;

namespace CallbackService.Client

{

    public class MyServiceCallback   : IMyServiceCallback

    {

        public void OnCallback()

        {

            Console.WriteLine(">   Received callback at {0}", DateTime.Now);

        }

    }

}

The client application is also a console application, so creating and using the proxy client will occur in its Program.Main. I added a pause to allow the server time to host the service, and then I invoke the remote procedure OpenSession. This will trigger the service to begin executing callbacks to the client application every second, resulting in a line written to the console. Here’s is the contents of my Program.cs:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

using System;

using System.ServiceModel;

namespace CallbackService.Client

{

    class Program

    {

        static void Main(string[]   args)

        {

            Console.WriteLine("Press   enter to continue once service is hosted.");

            Console.ReadLine();

            var callback   = new MyServiceCallback();

            var instanceContext   = new InstanceContext(callback);

            var client   = new MyServiceReference.MyServiceClient(instanceContext);

            client.OpenSession();

            Console.ReadLine();

        }

    }

}

Conclusion

And that’s all there is to it! This is clearly a simple, unorganized example with few complexities, but it demonstrates the core functionality provided by callbacks in WCF services. This capability allows for push updates and other real-time communication between client and server, and it really opens a world of possibilities. This is certainly a welcome option in my ever-growing development toolbox!

【转】一个简单的WCF回调实例的更多相关文章

  1. [WCF REST] 一个简单的REST服务实例

    Get:http://www.cnblogs.com/artech/archive/2012/02/04/wcf-rest-sample.html [01] 一个简单的REST服务实例 [02] We ...

  2. 一个简单的jQuery插件开发实例

    两年前写的一个简单的jQuery插件开发实例,还是可以看看的: <script type="text/javascript" src="jquery-1.7.2.m ...

  3. 一个简单的Android小实例

    原文:一个简单的Android小实例 一.配置环境 1.下载intellij idea15 2.安装Android SDK,通过Android SDK管理器安装或卸载Android平台   3.安装J ...

  4. PureMVC和Unity3D的UGUI制作一个简单的员工管理系统实例

    前言: 1.关于PureMVC: MVC框架在很多项目当中拥有广泛的应用,很多时候做项目前人开坑开了一半就消失了,后人为了填补各种的坑就遭殃的不得了.嘛,程序猿大家都不喜欢像文案策划一样组织文字写东西 ...

  5. [WCF学习笔记] 我的WCF之旅(1):创建一个简单的WCF程序

    近日学习WCF,找了很多资料,终于找到了Artech这个不错的系列.希望能从中有所收获. 本文用于记录在学习和实践WCF过程中遇到的各种基础问题以及解决方法,以供日后回顾翻阅.可能这些问题都很基础,可 ...

  6. 一个简单的window.onscroll实例

    鉴于better-scroll实现这个效果很复杂,想用最原生的效果来实现吸顶效果 一个简单的window.onscroll实例,可以应用于移动端 demo 一个简单的window.onscroll实例 ...

  7. WCF服务二:创建一个简单的WCF服务程序

    在本例中,我们将实现一个简单的计算服务,提供基本的加.减.乘.除运算,通过客户端和服务端运行在同一台机器上的不同进程实现. 一.新建WCF服务 1.新建一个空白解决方案,解决方案名称为"WC ...

  8. WCF入门, 到创建一个简单的WCF应用程序

    什么是WCF?  WCF, 英文全称(windows Communication Foundation) , 即为windows通讯平台. windows想到这里大家都知道了 , WCF也正是由微软公 ...

  9. WCF学习——构建一个简单的WCF应用(一)

    本文的WCF服务应用功能很简单,却涵盖了一个完整WCF应用的基本结构.希望本文能对那些准备开始学习WCF的初学者提供一些帮助. 在这个例子中,我们将实现一个简单的计算器和传统的分布式通信框架一样,WC ...

随机推荐

  1. 用户数以及psp

    小组名称:好好学习 小组成员:林莉  王东涵   胡丽娜   宫丽君 项目名称: 记账本 alpha发布48小时以后用户数如何,是否达到预期目标,为什么,是否需要改进,如何改进(或理性估算). 首先我 ...

  2. “Unable to open kernel device \\.\Global\vmx86

    启动vm中虚拟机中的时候,弹出窗口的时候,弹出窗口 Unable to open kernel device \\.\Global\vmx86;系统找不到指定的文件,Did you reboot af ...

  3. 使用FileReader对象的readAsDataURL方法来读取图像文件

    使用FileReader对象的readAsDataURL方法来读取图像文件   FileReader对象的readAsDataURL方法可以将读取到的文件编码成Data URL.Data URL是一项 ...

  4. [转帖]Kerberos简介

    1.  Kerberos简介 https://www.cnblogs.com/wukenaihe/p/3732141.html 1.1. 功能 一个安全认证协议 用tickets验证 避免本地保存密码 ...

  5. Mysql 5.7 报错 3534 错误

    需要先 执行 mysqld  --initialize 然后  mysqld --install 最后  net start mysql 即可启动服务 如果不执行第一步 则会报错

  6. LeetCode 717. 1-bit and 2-bit Characters

    We have two special characters. The first character can be represented by one bit 0. The second char ...

  7. 访问控制列表-ACL匹配规则

    1 .ACL匹配机制 首先,小编为大家介绍ACL匹配机制.上一期提到,ACL在匹配报文时遵循“一旦命中即停止匹配”的原则.其实,这句话就是对ACL匹配机制的一个高度的概括.当然,ACL匹配过程中,还存 ...

  8. hbase 自定义过滤器

    1.首先生成自定义过滤器,生成jar包,然后拷贝到服务器hbase目录的lib下. 1.1 自定义过滤器CustomFilter import com.google.protobuf.InvalidP ...

  9. C++ 构造函数初始化列表

    C++ 中类初始化列表执行顺序是按照定义的顺序执行,不是写在初始化列表的顺序执行 #include <bits/stdc++.h> using namespace std; class N ...

  10. 【刷题】BZOJ 5415 [Noi2018]归程

    www.lydsy.com/JudgeOnline/upload/noi2018day1.pdf Solution 考试的时候打的可持久化并查集,没调出来QAQ 后面知道了kruskal重构树这个东西 ...