原文地址:http://blog.csdn.net/is_zhoufeng/article/details/7641234

////wcf 接口
 
#region << 版 本 注 释 >>
/****************************************************
* 文 件 名:IServices.cs
* Copyright(c) 2011-2012 JiangGuoLiang
* CLR 版本: 4.0.30319.235
* 创 建 人:Server126
* 创建日期:2011-8-10 15:00:55
*******************************************************/
#endregion
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
 
namespace Host
{
    [ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(ICallBackServices))]
    public interface IServices
    {
       /// <summary>
       /// 注册客户端信息
       /// </summary>
        [OperationContract(IsOneWay = false)]
        void Register();
         
    } //End Host
 
    public interface ICallBackServices
    {
        /// <summary>
        /// 服务像客户端发送信息(异步)
        /// </summary>
        /// <param name="Message"></param>
        [OperationContract(IsOneWay = true)]
        void SendMessage(string Message);
    }
} // End IServices
//////end
 
////////实现接口
 
#region << 版 本 注 释 >>
/****************************************************
* 文 件 名:Services.cs
* Copyright(c) 2011-2012 JiangGuoLiang
* CLR 版本: 4.0.30319.235
* 创 建 人:Server126
* 创建日期:2011-8-10 15:01:07
*******************************************************/
#endregion
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Configuration;
 
namespace Host
{
    /// <summary>
    ///  实例使用Single,共享一个
    ///  并发使用Mutiple, 支持多线程访问(一定要加锁)
    /// </summary>
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class Services : IServices
    {
        public static readonly string SendMessageType = ConfigurationManager.ConnectionStrings["SendMessageType"].ToString();
        private static readonly object InstObj = new object();//单一实例
        //public static List<ICallBackServices> RegList = null;
        public static Dictionary<string, ICallBackServices> DicHost = null; //记录机器名称
        public static Dictionary<string, ICallBackServices> DicHostSess = null;//记录Sessionid
        public Services()
        {
            //RegList = new List<ICallBackServices>();
            DicHost = new Dictionary<string, ICallBackServices>();
            DicHostSess = new Dictionary<string, ICallBackServices>();
        }
        #region IServices 成员
 
        public void Register()
        {
            ICallBackServices client = OperationContext.Current.GetCallbackChannel<ICallBackServices>();
            string sessionid = OperationContext.Current.SessionId;//获取当前机器Sessionid--------------------------如果多个客户端在同一台机器,就使用此信息。
            string ClientHostName = OperationContext.Current.Channel.RemoteAddress.Uri.Host;//获取当前机器名称-----多个客户端不在同一台机器上,就使用此信息。
            OperationContext.Current.Channel.Closing += new EventHandler(Channel_Closing);//注册客户端关闭触发事件
            if (SendMessageType.ToUpper() == "SESSIONID")
            {
                DicHostSess.Add(sessionid, client);//添加
            }
            else
            {
                DicHost.Add(ClientHostName, client); //添加
            }
            //RegList.Add(client);//添加
        }
        void Channel_Closing(object sender, EventArgs e)
        {
            lock (InstObj)//加锁,处理并发
            {
                //if (RegList != null && RegList.Count > 0)
                //    RegList.Remove((ICallBackServices)sender);
                if (SendMessageType.ToUpper() == "SESSIONID")
                {
                    if (DicHostSess != null && DicHostSess.Count > 0)
                    {
                        foreach (var d in DicHostSess)
                        {
                            if (d.Value == (ICallBackServices)sender)//删除此关闭的客户端信息
                            {
                                DicHostSess.Remove(d.Key);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    if (DicHost != null && DicHost.Count > 0) //同上
                    {
                        foreach (var d in DicHost)
                        {
                            if (d.Value == (ICallBackServices)sender)
                            {
                                DicHost.Remove(d.Key);
                                break;
                            }
                        }
                    }
                }
            }
        }
 
 
 
        #endregion
 
 
 
    } //End Host
} //End Services
 
 
////host
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using System.Threading;
 
namespace Host
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private static readonly object InstObj = new object();
        private static bool isval = true;
        private void Form1_Load(object sender, EventArgs e)
        {
            ServiceHost host = new ServiceHost(typeof(Services));
            host.Open();
            this.Text = "wcf starte aucceeded !";
 
            #region init listbox
            Thread thread = new Thread(new ThreadStart(delegate   ///监听所有客户端连接,并添加到ListBox控件里
            {
                lock (InstObj)//加锁
                {
                    while (true)
                    {
 
                        if (Services.SendMessageType.ToUpper() == "SESSIONID")
                        {
                            if (Services.DicHostSess != null || Services.DicHostSess.Count > 0)
                            {
                                this.Invoke(new MethodInvoker(delegate { this.listBox1.Items.Clear(); }));
                                foreach (var l in Services.DicHostSess)
                                {
                                    this.Invoke(new MethodInvoker(delegate
                                    {
                                        this.listBox1.Items.Add(l.Key);
                                    }));
                                }
                            }
                        }
                        else
                        {
                            if (Services.DicHost != null || Services.DicHost.Count > 0)
                            {
                                this.Invoke(new MethodInvoker(delegate { this.listBox1.Items.Clear(); }));
                                foreach (var l in Services.DicHost)
                                {
                                    this.Invoke(new MethodInvoker(delegate
                                    {
                                        this.listBox1.Items.Add(l.Key);
                                    }));
                                }
                            }
                        }
                        Thread.Sleep(1000 * 10);
                    }
                }
            }));
            thread.IsBackground = true;
            thread.Start();
            #endregion
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            if (Services.DicHostSess == null || Services.DicHostSess.Count > 0)
            {
                if (this.listBox1.SelectedItem != null)
                {
                    if (this.listBox1.SelectedItem.ToString() != "")
                    {
                        foreach (var d in Services.DicHostSess)
                        {
                            if (d.Key == this.listBox1.SelectedItem.ToString())
                            {
                                d.Value.SendMessage(string.Format("Time: {0} message {1}", DateTime.Now, "abc"));
                            }
                        }
                    }
                }
                else { MessageBox.Show("请选择要推送给哪台客户端"); return; }
            }
            if (Services.DicHost != null || Services.DicHost.Count > 0)
            {
                if (this.listBox1.SelectedItem != null)
                {
                    if (this.listBox1.SelectedItem.ToString() != "")
                    {
                        foreach (var d in Services.DicHost)
                        {
                            if (d.Key == this.listBox1.SelectedItem.ToString())
                            {
                                d.Value.SendMessage(string.Format("Time: {0} message {1}", DateTime.Now, "abc"));
                            }
                        }
                    }
                }
                else { MessageBox.Show("请选择要推送给哪台客户端"); return; }
            }
        }
        //广播方式
        private void button2_Click(object sender, EventArgs e)
        {
            if (Services.SendMessageType.ToUpper() == "SESSIONID")//类型
            {
                foreach (var d in Services.DicHostSess)
                {
                    d.Value.SendMessage(this.textBox1.Text);
                }
            }
            else
            {
                foreach (var d in Services.DicHost)
                {
                    d.Value.SendMessage(this.textBox1.Text);
                }
            }
        }
 
    }
}
////client
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
 
namespace client
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("create object...");
                CallBack back = new CallBack();
                InstanceContext context = new InstanceContext(back);
                ServiceReference1.ServicesClient client = new ServiceReference1.ServicesClient(context);
                Console.WriteLine("regist.....");
                client.Register();
                Console.WriteLine("aucceeded");
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); }
            Console.ReadKey();
            client.Close();//关闭。
        }
    }
    class CallBack : ServiceReference1.IServicesCallback
    {
        #region IServicesCallback 成员
 
        public void SendMessage(string Message)
        {
            Console.WriteLine("[ClientTime{0:HHmmss}]Service Broadcast:{1}", DateTime.Now, Message);
        }
 
        #endregion
    }
 
}

  下载地址:http://download.csdn.net/source/3511270

wcf 推送 与 广播的更多相关文章

  1. springboot整合websocket实现一对一消息推送和广播消息推送

    maven依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  2. springboot集成websocket点对点推送、广播推送

    一.什么都不用说,导入个依赖先 <dependency> <groupId>org.springframework.boot</groupId> <artif ...

  3. WCF推送

    http://www.cnblogs.com/server126/archive/2011/08/11/2134942.html

  4. 使用用WCF中的双工(Duplex)模式将广告图片推送到每个Winform客户端机子上

    参考资料地址:http://www.cnblogs.com/server126/archive/2011/08/11/2134942.html 代码实现: WCF宿主(服务端) IServices.c ...

  5. Asp.NET MVC 中使用 SignalR 实现推送功能

    一,简介Signal 是微软支持的一个运行在 Dot NET 平台上的 html websocket 框架.它出现的主要目的是实现服务器主动推送(Push)消息到客户端页面,这样客户端就不必重新发送请 ...

  6. 在 Asp.NET MVC 中使用 SignalR 实现推送功能

    一,简介Signal 是微软支持的一个运行在 Dot NET 平台上的 html websocket 框架.它出现的主要目的是实现服务器主动推送(Push)消息到客户端页面,这样客户端就不必重新发送请 ...

  7. MVC 中使用 SignalR 实现推送功能

    MVC 中使用 SignalR 实现推送功能 一,简介 Signal 是微软支持的一个运行在 Dot NET 平台上的 html websocket 框架.它出现的主要目的是实现服务器主动推送(Pus ...

  8. 在 Asp.NET MVC 中使用 SignalR 实现推送功能 [转]

    在 Asp.NET MVC 中使用 SignalR 实现推送功能 罗朝辉 ( http://blog.csdn.net/kesalin ) CC许可,转载请注明出处 一,简介 Signal 是微软支持 ...

  9. 史上最全面的SignalR系列教程-2、SignalR 实现推送功能-永久连接类实现方式

    1.概述 通过上篇史上最全面的SignalR系列教程-1.认识SignalR文章的介绍,我们对SignalR技术已经有了一个全面的了解.本篇开始就通过SignalR的典型应用的实现方式做介绍,例子虽然 ...

随机推荐

  1. MySQL查询缓存

    MySQL查询缓存 用于保存MySQL查询语句返回的完整结果,被命中时,MySQL会立即返回结果,省去解析.优化和执行等阶段. 如何检查缓存? MySQL保存结果于缓存中: 把SELECT语句本身做h ...

  2. chosen组件实现下拉框

    chosen组件用于增强原生的select控件,使之有更好的用户体验.官方demo https://harvesthq.github.io/chosen/ 目前项目中碰到的使用,比如一个页面中有两个不 ...

  3. Ext.Net 学习随笔 002 默认按钮

    在FormPanel中按回车按键,会触发默认按钮的click事件.设置方法为在FormPanel中设置DefaultButton属性,如果没有设置这个属性,默认为最后一个按钮. 1.缺省最后一个按钮为 ...

  4. SQL NOT EXISTS

    看了一篇文章,虽然知识点很简单,但是还是帮我理解了一些以前没想到的东西 一共三个表student,class,score create table student(sno varchar(50) no ...

  5. Dubbo 与 ImmutableList冲突解决

    在Java web实际开发中,常常用到微服务来进行架构分离,今天遇到一特奇怪的问题,Dububo 调用了接口三次,provider端而且没有抛出Exception.consumer却端抛出调用失败的异 ...

  6. Window.Open详解

    文章来源:http://www.cnblogs.com/stswordman/archive/2006/06/02/415853.html 一.window.open()支持环境:JavaScript ...

  7. 安装oracle数据库,登录 时无法连接目标机

    oracle11g 在dos命令里输入输入sqlplus 输入如用户名: 输入口令: 还是无法连接 解决办法: 输入sqlplus/nolog按enter键再输入conn/as sysdba就好了

  8. [API]使用Blueprint来高雅的编写接口文档 前后端api文档,移动端api文档

    网址:http://apiary.io/ 介绍:一款非常强大的前后端交互api设计编辑工具(编辑器采用Markdown类似的描述标记,非常高效),高颜值的api文档,还能生成多种语言的测试代码. 中文 ...

  9. app升级方法

    1.到那里找apk? (1)Android Studio菜单Build->Generate Signed APK     (2)弹出窗口     (3)创建密钥库及密钥,创建后会自动选择刚创建的 ...

  10. jsp脚本元素

    在JSP页面中有三种脚本元素(Scripting Elements):声明.小脚本和表达式. 声明(declaration)用来在JSP页面中声明变量和定义方法.声明是以<%!开头,以%> ...