很多时候我们会遇到,信息及时推送通知的情况,例如:监控设备时及时推送状态、报警信息等,我们就可以用WCF的回调机制来实现,下面以一个监控设备名字为例,如果设备名字发生改变,服务器就马上推送消息给客户端:
(一、)服务器端

1、建一个控制台应用程序:CallbackContractWCF
2、创建ISendMessage接口

namespace CallbackContractWCF
{
[ServiceContract(CallbackContract = typeof(IMessageCallbackContract))]
public interface ISendMessage
{
///
/// 保存客户端回调的实例
///
[OperationContract]
void Subscribe();
}
}

3、创建用于推送消息回调的接口IMessageCallbackContract

namespace CallbackContractWCF
{
public interface IMessageCallbackContract
{
[OperationContract(IsOneWay = true)]
void ReportMes(string responseToGreeting);
}
}

4、创建实现接口ISendMessage的类SendMessage

 namespace CallbackContractWCF
{
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single,ConcurrencyMode=ConcurrencyMode.Multiple,UseSynchronizationContext=false)]
public class SendMessage:ISendMessage
{
private System.Timers.Timer _setValueTimer;
private IMessageCallbackContract callerProxy = null;
~SendMessage()
{
_setValueTimer.Stop();
Device.OnChange -= new Action(Student_OnChange);
}
public SendMessage()
{
Thread.Sleep();
_setValueTimer = new System.Timers.Timer();
_setValueTimer.AutoReset = true;
_setValueTimer.Elapsed += Timer_Elapsed;
_setValueTimer.Interval = ;
_setValueTimer.Start();
Device.OnChange += new Action(Student_OnChange);
}
//保存客户端回调的实例
public void Subscribe()
{
try
{
//获取当前调用的核心服务端实例的通道
callerProxy = OperationContext.Current.GetCallbackChannel();
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
Random rand = new Random();
string name = "路由器"+rand.Next();
SetName(name);
}
private void SetName(string greeting)
{
if (greeting != Device.Name)
{
Device.Name = greeting;
Device.Change(greeting);
}
}
void Student_OnChange(string name)
{
try
{
Console.Write("只要名字与当前的不同就向客户端推送通知\r\n");
callerProxy.ReportMes(name);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
}
//创建设备类
public static class Device
{
public static string Name { get; set; }
public static event Action OnChange;
public static void Change(string name)
{
if (OnChange != null)
{
OnChange.Invoke(name);
}
}
}
}

5、添加配置文件App.config

<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="behavior1">
<serviceMetadata httpGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors> <bindings>
<netTcpBinding>
<binding name="BigBinding" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00"
sendTimeout="00:10:00" transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard" listenBacklog="10" maxBufferPoolSize="524288000"
maxBufferSize="65536000" maxConnections="10" maxReceivedMessageSize="65536000"> <readerQuotas maxDepth="32000" maxStringContentLength="8192000"
maxArrayLength="16384000" maxBytesPerRead="4096000"
maxNameTableCharCount="16384000"/>
<reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false"/>
<security mode="None"/>
</binding>
<binding name="netTcpBinding_ISendMessage">
<security mode="None"></security>
</binding>
</netTcpBinding>
</bindings> <services>
<service name="CallbackContractWCF.SendMessage" behaviorConfiguration="behavior1">
<endpoint address="SendMessage" binding="netTcpBinding" bindingConfiguration="BigBinding"
contract="CallbackContractWCF.ISendMessage" name="netTcpBinding_ISendMessage" >
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:8729/Design_Time_Addresses/CallbackContractWCF/SendMessage/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>

(二、)客户端
1、创建控制台应用程序CallbackContractClient
2、启动服务器,添加服务引用
3、创建一个实现服务器端回调接口的类MessageCallback

namespace CallbackContractClient
{
[System.ServiceModel.CallbackBehavior(IncludeExceptionDetailInFaults = true, UseSynchronizationContext = false, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class MessageCallback : ISendMessageCallback
{
public event Action OnReportMes; //实现服务端的回调
public void ReportMes(string responseMes)
{
if (OnReportMes != null)
{
OnReportMes.Invoke(responseMes);
}
}
}
}

4、在控制台主程序Program.cs中挂载服务

namespace CallbackContractClient
{
class Program
{
static void Main(string[] args)
{
MessageCallback callback=new MessageCallback ();
callback.OnReportMes+=new Action(callback_OnReportMes);
InstanceContext content = new InstanceContext(callback);
SendMessageClient clicent = new SendMessageClient(content);
clicent.Subscribe(); Console.Write("监控设备");
Console.ReadLine();
} public static void callback_OnReportMes(string res)
{
Console.Write("\r\n设备的名称为:" + res);
Console.ReadLine();
}
}
}

(三、)监测结果

WCF的回调使用实例代码说明的更多相关文章

  1. 阿里云OSS C#回调服务实例代码

    先贴出客户端上传文件代码和毁掉函数的定义 需要的引用有:using Aliyun.OSS: 通过nuget包,获取aliyun.oss   dll string url = "http:// ...

  2. 浅议Grpc传输机制和WCF中的回调机制的代码迁移

    浅议Grpc传输机制和WCF中的回调机制的代码迁移 一.引子 如您所知,gRPC是目前比较常见的rpc框架,可以方便的作为服务与服务之间的通信基础设施,为构建微服务体系提供非常强有力的支持. 而基于. ...

  3. WCF会话(Session)与实例(Instance)管理

    一.理解Session 1.Session的作用:保留Client和Service之间交互的状态,确保Client与Service之间交互唯一性(SessionId),即:多个Client同时访问Se ...

  4. asp.net中生成缩略图并添加版权实例代码

    这篇文章介绍了asp.net中生成缩略图并添加版权实例代码,有需要的朋友可以参考一下 复制代码代码如下: //定义image类的对象 Drawing.Image image,newimage; //图 ...

  5. 模拟jQuery中的ready方法及实现按需加载css,js实例代码

    这篇文章介绍了模拟jQuery中的ready方法及实现按需加载css,js实例代码,有需要的朋友可以参考一下     一.ready函数的实现经常用jQuery类库或其他类库中的ready方法,有时候 ...

  6. WCF通信简单学习实例

    最近在学习WCF通信,自己简单做个实例分享一下,环境是VS2015,使用的项目都是WPF的项目,其实大家用Winform或者Web项目也可以,都可以用的. 一.服务器端 1.创建WCF服务 服务名为W ...

  7. jQuery Ajax方法调用 Asp.Net WebService、WebMethod 的详细实例代码

    将以下html存为ws.aspx <%@ Page Language="C#" AutoEventWireup="true" %> <scri ...

  8. [WCF编程]8.服务实例的生命周期

    一.服务实例的生命周期概览 我们已经直到,通过显式调用Close方法或等待默认的超时时间到来,都可以释放服务实例.但是,在会话连接里,经常需要按一定顺序调用方法. 二.分步操作 会话契约的操作有时隐含 ...

  9. C++11 变长模版和完美转发实例代码

    C++11 变长模版和完美转发实例代码 #include <memory>#include <iostream>#include <vector>#include ...

随机推荐

  1. OC语法简写

    NSNumber [NSNumber numberWithInt:666] 等价于 @666 [NSNumber numberWithLongLong:666ll] 等价于 @666ll [NSNum ...

  2. Swift - 20 - 字典的基础操作

    //: Playground - noun: a place where people can play import UIKit var dict = [1:"one", 2:& ...

  3. JVM调优实践-Tomcat调优

    调优几个重要指标 GC频率 提升每次GC的效率 准备环节 jmeter的配置 未压测前JVM配置 工程未调优前配置 -Xms400m -Xmx400m -XX:PermSize=64m -XX:Max ...

  4. 基于ThinkPHP+AJAX的省市区三级联动

    练习,就当练习. 省市区三级联动,样式如下图所示: 1,导入两个js文件并且导入数据库文件. 两个js文件分别是jquery-2.1.4.min.js和jquery-1.js,数据库文件,见附件. 2 ...

  5. w3wp异常

    相信做ASP.NET中大型Web应用的人都碰到过OutOfMemoryException这个异常,对于这个问题我研究了很久,在微软的技术文档上也了解过此问题出现的原因,说实话,到目前我仍然没有完美的解 ...

  6. C语言对数组取地址

    #include <stdio.h> main() { ] = {,,,,}; printf("a=%p\n" , a); printf("a=%p\n&qu ...

  7. UIImageView设置为圆形

       CGFloat headimageX = self.view.frame.size.width * 0.2; CGFloat headimageY = self.view.frame.size. ...

  8. Solr4.8.0源码分析(14)之SolrCloud索引深入(1)

    Solr4.8.0源码分析(14) 之 SolrCloud索引深入(1) 上一章节<Solr In Action 笔记(4) 之 SolrCloud分布式索引基础>简要学习了SolrClo ...

  9. 转:cookie和session(二)——php应用

    文章来自于:http://blog.csdn.net/half1/article/details/21650211 本文将介绍cookie在session在php中的基本用法. 1.cookie   ...

  10. Seek the Name, Seek the Fame

    poj2752:http://poj.org/problem?id=2752 题意:给你一个串,让你求前n个字符和后n个字符相同的n有多少,从小到大输出来. 题解:这一题要深刻理解KMP的next数组 ...