源码下载

程序分四个部分:

1、原理

使用WCF的nettcp绑定。nettcp绑定类似原来的RPC,即.net remoting,只是在WCF提供统一协定,同一服务可以拥有多种客户端。

2、代码展示

代码部分分为契约、服务、服务端UI、客户端四个部分。

2.1、契约部分

定义服务的接口,一个提供服务,另一个提供回调。

服务端接口定义:

    [ServiceContract(
Name = "SampleDuplexHello",
Namespace = "http://microsoft.wcf.documentation",
CallbackContract = typeof(IHelloCallbackContract),
SessionMode = SessionMode.Required
)]
public interface IDuplexHello
{
/// <summary>
/// 往服务端发送消息
/// </summary>
/// <param name="greeting"></param>
[OperationContract(IsOneWay = true)]
void Hello(string greeting); /// <summary>
/// 让服务端缓存客户端
/// </summary>
[OperationContract]
void Registor();
}

服务端回调接口定义:

    /// <summary>
/// 回调接口
/// </summary>
public interface IHelloCallbackContract
{
/// <summary>
/// 向客户端推送消息
/// </summary>
/// <param name="responseToGreeting"></param>
[OperationContract(IsOneWay = true)]
void Reply(string responseToGreeting);
}

2.2、服务实现部分

代码部分:

    public class DuplexHelloImpl : IDuplexHello, IBrocaster
{
private ConcurrentBag<IHelloCallbackContract> clients = new ConcurrentBag<IHelloCallbackContract>(); 。。。 public void Hello(string greeting)
{
if (ServerInstance != null)
{
ServerInstance.Update(greeting);
}
} public void Registor()
{
IHelloCallbackContract callerProxy
= OperationContext.Current.GetCallbackChannel<IHelloCallbackContract>();
if (!clients.Contains(callerProxy))
{
clients.Add(callerProxy);
}
}
}

配置部分:

  <system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="NewBinding0">
<security mode="None"/>
</binding>
</netTcpBinding>
</bindings>
<services> <service name="WindowsFormsServer.DuplexHelloImpl">
<endpoint address="net.tcp://localhost:909/hello" bindingConfiguration="NewBinding0" binding="netTcpBinding" contract="Contracts.IDuplexHello"/> </service>
</services>
</system.serviceModel>

启动部分:

      static void Main()
{
ServiceHost host = new ServiceHost(typeof(DuplexHelloImpl));
host.Open(); 。。。
}

2.3、服务端界面

 public partial class ServerForm : Form, IUpdater
{
public static IBrocaster ServiceInstance { get; set; } public ServerForm()
{
InitializeComponent();
} public void Update(string content)
{
this.Invoke(new Action(() =>
{
this.textBox2.AppendText(content);
this.textBox2.AppendText("\r\n");
}));
} private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
if (ServiceInstance == null)
{
MessageBox.Show("服务启动中,稍后再发!");
return;
}
ServiceInstance.Brocast(textBox1.Text);
textBox1.Text = "";
}
else
MessageBox.Show("回复内容不能为空!");
} private void ServerForm_Load(object sender, EventArgs e)
{
//Service与主窗体非同步,因而需要等待
Task.Run(() => {
while (ServiceInstance == null)
{
Thread.Sleep();
}
ServiceInstance.ServerInstance = this;
});
}
}

2.4、客户端界面

public partial class ClientForm : Form, IHelloCallbackContract
{
/// <summary>
/// 定义为字段,以供重用。
/// </summary>
IDuplexHello client;
public ClientForm()
{
InitializeComponent();
} public void Reply(string responseToGreeting)
{
this.textBox2.AppendText(responseToGreeting);
this.textBox2.AppendText("\r\n");
} private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
client.Hello(textBox1.Text);
textBox1.Text = "";
}
else
MessageBox.Show("回复内容不能为空!"); } private void ClientForm_Load(object sender, EventArgs e)
{
//创建连接
InstanceContext cxt = new InstanceContext(this);
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.None;
string url = "net.tcp://localhost:909/hello";
DuplexChannelFactory<IDuplexHello> factory =
new DuplexChannelFactory<IDuplexHello>(cxt, binding, url); client = factory.CreateChannel();
client.Registor();
}
}

WCF 双向通讯实例-简易的聊天程序的更多相关文章

  1. silverlight与wcf双向通讯 例子

    本文将建立一个silverlight与wcf双向通讯的简单实例,以下是详细步骤: 新建Silverlight应用程序,名称WCFtest.解决方案中添加WCF服务应用程序,名称WcfServiceTe ...

  2. 基于UDP协议的控制台聊天程序(c++版)

    本博客由Rcchio原创,转载请告知作者 ------------------------------------------------------------------------------- ...

  3. C# 异步通信 网络聊天程序开发 局域网聊天室开发

    Prepare 本文将使用一个NuGet公开的组件技术来实现一个局域网聊天程序,利用组件提供的高性能异步网络机制实现,免去了手动编写底层的困扰,易于二次开发,扩展自己的功能. 在Visual Stud ...

  4. 重温WCF之数单向通讯、双向通讯、回调操作(五)

    一.单向通讯单向操作不等同于异步操作,单向操作只是在发出调用的瞬间阻塞客户端,但如果发出多个单向调用,WCF会将请求调用放入到服务器端的队列中,并在某个时间进行执行.队列的存储个数有限,一旦发出的调用 ...

  5. boost asio异步读写网络聊天程序client 实例具体解释

    boost官方文档中聊天程序实例解说 数据包格式chat_message.hpp <pre name="code" class="cpp">< ...

  6. boost asio异步读写网络聊天程序客户端 实例详解

    boost官方文档中聊天程序实例讲解 数据包格式chat_message.hpp <pre name="code" class="cpp">< ...

  7. 我们一起学习WCF 第四篇单通讯和双向通讯

    前言:由于个人原因很久没有更新这个系列了,我会继续的更新这系列的文章.这一章是单向和双向通讯.所谓的单向就是只有发送却没有回复,双向是既有发送还有回复.就是有来无往代表单向,礼尚往来表示双向.下面我用 ...

  8. 编写Java程序,应用客户端和服务端通过 Eclipse 控制台的输入和显示实现简易的聊天功能

    查看本章节 查看作业目录 需求说明: 应用客户端和服务端通过 Eclipse 控制台的输入和显示实现简易的聊天功能 实现思路: 创建 Java 项目,在项目中创建服务端类 ChatServerThre ...

  9. 三十、【C#.Net开发框架】WCFHosting服务主机的利用WCF服务通讯和实现思路

    回<[开源]EFW框架系列文章索引>        EFW框架源代码下载V1.3:http://pan.baidu.com/s/1c0dADO0 EFW框架实例源代码下载:http://p ...

随机推荐

  1. 问题小记(MyBatis传参出现的小问题)

    问题一:在MyBatis中注解@Param和ParameterType不能一起用,会报错Parameter 'XXX' not found. Available parameters are [1, ...

  2. SQLSTATE[HY000] [2002] No such file or directory in

    这个错误将数据库配置信息的localhost改成127.0.0.1就行了

  3. 设计模式入门,工厂模式,c++代码实现

    // test04.cpp : Defines the entry point for the console application.////设计模式第4章 工厂模式#include "s ...

  4. Grunt usemin前端自动化打包流程

    前端优化是尽量减少http请求,所以我们需要尽量合并压缩文件,然后调用压缩后的文件,比如多个css文件压缩成一个,多个js文件合并压缩等,usemin能够自动在html中使用压缩后的文件,达到上面的目 ...

  5. HDU4336:Card Collector(min-max容斥)

    题面 传送门 Sol 方法一 直接状压就好了 # include <bits/stdc++.h> # define RG register # define IL inline # def ...

  6. 【转】B树、B-树、B+树、B*树、红黑树、 二叉排序树、trie树Double Array 字典查找树简介

    B  树 即二叉搜索树: 1.所有非叶子结点至多拥有两个儿子(Left和Right): 2.所有结点存储一个关键字: 3.非叶子结点的左指针指向小于其关键字的子树,右指针指向大于其关键字的子树: 如: ...

  7. 如何编写自定义hive UDF函数

    Hive可以允许用户编写自己定义的函数UDF,来在查询中使用.Hive中有3种UDF: UDF:操作单个数据行,产生单个数据行: UDAF:操作多个数据行,产生一个数据行. UDTF:操作一个数据行, ...

  8. javascprit form表单提交前验证以及ajax返回json

    1.今天要做一个手机验证码验证的功能.需求是前端页面点击发送 短信验证码,后台接收后通过ajax返回到前端,之后前端在提交时候进行验证.思路很简单,不过做的过程还是学到不少的东西. 1.ajax请求后 ...

  9. WebLogic如何设置session超时时间

    1.web.xml  设置WEB应用程序描述符web.xml里的<session-timeout>元素.这个值以分钟为单位,并覆盖weblogic.xml中的TimeoutSecs属性   ...

  10. 微软智能云的核心DNA

    你知道吗? 今天,微软智能云平台运行于全球30个区域,体量超过了两大云服务商亚马逊和谷歌的总和: 今天,在全球范围内超过85%的财富五百强企业都使用了微软Azure云服务,而中国部分的用户也达到了六万 ...