代码下载: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. angularJS1笔记-(14)-自定义指令(scope)

    index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset=&qu ...

  2. rpm安装和二进制安装

    rpm包安装 Tomcat RPM安装(先安装JDK + 再安装Tomcat) 1:升级系统自带的JDK(也可以使用oracle的JDK) yum install -y java-1.8.0-open ...

  3. JPEG图像压缩算法流程详解

    JPEG图像压缩算法流程详解 JPEG代表Joint Photographic Experts Group(联合图像专家小组).此团队创立于1986年,1992年发布了JPEG的标准而在1994年获得 ...

  4. D3.js 入门学习(二) V4的改动

    //d3.scan /* 新的d3.scan方法对数组进行线性扫描,并根据指定的比较函数返回至少一个元素的索引. 这个方法有点类似于d3.min和d3.max. 而d3.scan可以得到极值的索引而不 ...

  5. [转帖]高通推出八核笔电处理器骁龙8cx 能超英特尔吗?

    高通推出八核笔电处理器骁龙8cx 能超英特尔吗? https://baijiahao.baidu.com/s?id=1619154699684981202&wfr=spider&for ...

  6. JS贪吃蛇小游戏

    效果图展示: 具体实现代码如下: (1)html部分 !DOCTYPE html> <html> <head> <meta charset="utf-8& ...

  7. 程序集里包含多个版本dll引用 ,强制低版本到制定版本dll引用

    在 config 的 <configuration> 节点内加入以下 类似信息 以下是以Newtonsoft.Json 为例子 <runtime> <assemblyBi ...

  8. iOS 数据库sqlite完整增删改查操作

    1: 创建数据库表格 1.1 — 表格创建使用一个数据库软件快速创建:软件大小14.3M; 下载地址:http://pan.baidu.com/s/1qWOgGoc; 表格创建-> 打开软件,点 ...

  9. BZOJ 3173 最长上升子序列(树状数组+二分+线段树)

    给定一个序列,初始为空.现在我们将1到N的数字插入到序列中,每次将一个数字插入到一个特定的位置.每插入一个数字,我们都想知道此时最长上升子序列长度是多少? 由于序列是顺序插入的,所以当前插入的数字对之 ...

  10. BZOJ4519 CQOI2016不同的最小割(最小割+分治)

    最小割树:新建一个图,包含原图的所有点,初始没有边.任取两点跑最小割,给两点连上权值为最小割的边,之后对于两个割集分别做同样的操作.最后会形成一棵树,树上两点间路径的最小值即为两点最小割.证明一点都不 ...