一、WCF入门

1. 新建立空白解决方案,并在解决方案中新建项目,项目类型为:WCF服务应用程序,删除系统生成的两个文件IService1.cs与Service1.svc, 添加自定义的WCF【服务文件】User.svc。建立完成后如下图所示:

2、在IUser.cs中添加方法ShowName接口和在User.svc中时间方法,如图:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text; namespace WcfServer
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IUser”。
[ServiceContract]
public interface IUser
{
[OperationContract]
string ShowName(string name);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text; namespace WcfServer
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“User”。
public class User : IUser
{
public string ShowName(string name)
{
string wcfName = string.Format("WCF服务,显示姓名:{0}", name);
return wcfName;
}
}
}

大家可以看到,在WCF中的接口与普通接口的区别只在于两个上下文,其他的和我们正常学习的接口一样。定义这个上下文要添加System.ServiceModel的引用。

[ServiceContract],来说明接口是一个WCF的接口,如果不加的话,将不能被外部调用。

[OperationContract],来说明该方法是一个WCF接口的方法,不加的话同上。

此时我们的第一个WCF服务程序就建立好了,将User.svc“设为起始页”,然后F5运行一下试试,如下图所示,VS2010自动调用了WCF的客户端测试工具以便我们测试程序:

我们双击上图中的 ShowName() 方法,测试一下方法,出现如下图:

4、在游览器中出现如下图所示,说明服务部署成功。

二、客户端动态调用WCF

1、新建WinForm程序,添加WCF访问接口类:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Reflection; namespace WcfClient
{
/// <summary>
/// 使用ChannelFactory为wcf客户端创建独立通道
/// </summary>
public class WcfChannelFactory
{
public WcfChannelFactory()
{
} /// <summary>
/// 执行方法 WSHttpBinding
/// </summary>
/// <typeparam name="T">服务接口</typeparam>
/// <param name="uri">wcf地址</param>
/// <param name="methodName">方法名</param>
/// <param name="args">参数列表</param>
public static object ExecuteMetod<T>(string uri, string methodName, params object[] args)
{
//BasicHttpBinding binding = new BasicHttpBinding(); //出现异常:远程服务器返回错误: (415) Cannot process the message because the content type 'text/xml; charset=utf-8' was not the expected type 'application/soap+xml; charset=utf-8'.。
WSHttpBinding binding = new WSHttpBinding();
EndpointAddress endpoint = new EndpointAddress(uri); using (ChannelFactory<T> channelFactory = new ChannelFactory<T>(binding, endpoint))
{
T instance = channelFactory.CreateChannel();
using (instance as IDisposable)
{
try
{
Type type = typeof(T);
MethodInfo mi = type.GetMethod(methodName);
return mi.Invoke(instance, args);
}
catch (TimeoutException)
{
(instance as ICommunicationObject).Abort();
throw;
}
catch (CommunicationException)
{
(instance as ICommunicationObject).Abort();
throw;
}
catch (Exception vErr)
{
(instance as ICommunicationObject).Abort();
throw;
}
}
} } //nettcpbinding 绑定方式
public static object ExecuteMethod<T>(string pUrl, string pMethodName,params object[] pParams)
{
EndpointAddress address = new EndpointAddress(pUrl);
Binding bindinginstance = null;
BasicHttpBinding ws = new BasicHttpBinding();
ws.MaxReceivedMessageSize = ;
bindinginstance = ws;
using (ChannelFactory<T> channel = new ChannelFactory<T>(bindinginstance, address))
{
T instance = channel.CreateChannel();
using (instance as IDisposable)
{
try
{
Type type = typeof(T);
MethodInfo mi = type.GetMethod(pMethodName);
return mi.Invoke(instance, pParams);
}
catch (TimeoutException)
{
(instance as ICommunicationObject).Abort();
throw;
}
catch (CommunicationException)
{
(instance as ICommunicationObject).Abort();
throw;
}
catch (Exception vErr)
{
(instance as ICommunicationObject).Abort();
throw;
}
}
}
}
}
}

2、添加接口IUser.cs文件,把服务端的IUser.cs文件拷贝过来:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text; namespace WcfClient
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IUser”。
[ServiceContract]
public interface IUser
{
[OperationContract]
string ShowName(string name);
}
}

3、调用

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; namespace WcfClient
{
public partial class Form1 : Form
{ public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
string uri = "http://localhost:32904/User.svc?wsdl";
object o = WcfChannelFactory.ExecuteMethod<IUser>(uri, "ShowName", this.textBox1.Text.Trim());
this.label1.Text = string.Format("服务:{0}", o.ToString()); } }
}

4结果如图:

调用:

注意:WCF的bing方式,根据服务器的配置来,选择合适的bing方式:

WCF中常用的binding方式:

BasicHttpBinding: 用于把 WCF 服务当作 ASMX Web 服务。用于兼容旧的Web ASMX 服务。
WSHttpBinding: 比 BasicHttpBinding 更加安全,通常用于 non-duplex 服务通讯。
WSDualHttpBinding: 和 WSHttpBinding 相比,它支持 duplex 类型的服务。
WSFederationHttpBinding: WS-Federation 安全通讯协议。
NetTcpBinding: 使用 TCP 协议,用于在局域网(Intranet)内跨机器通信。有几个特点:可靠性、事务支持和安全,优化了 WCF 到 WCF 的通信。限制是服务端和客户端都必须使用 WCF 来实现。
NetNamedPipeBinding: 使用命名管道进行安全、可靠、高效的单机服务通讯方式。
NetMsmqBinding: 使用消息队列在不同机器间进行非连接通讯。
NetPeerTcpBinding: 使用 P2P 协议在多机器间通讯。
MsmqIntegrationBinding: 将 WCF 消息转化为 MSMQ 消息,使用现有的消息队列系统进行跨机器通讯。如MSMQ。

名称

传输

编码

共同操作

BasicHttpBinding

HTTP/HTTPS

Text

Yes

NetTcpBinding

TCP

Binary

No

NetPeerTcpBinding

P2P

Binary

No

NetNamedPipeBinding

IPC

Binary

No

WSHttpBinding

HTTP/HTTPS

Text,MTOM

Yes

WSFederationBinding

HTTP/HTTPS

Text,MTOM

Yes

WSDualHttpBinding

HTTP

Text,MTOM

Yes

NetMsmqBinding

MSMQ

Binary

No

MsmqIntegrationBinding

MSMQ

Binary

Yes

Binding名称

Configuration Element

描述

BasicHttpBinding

basicHttpBinding

一个指定用符合基本网络服务规范通讯的binding,它用http进行传输,数据格式为text/xml

WSHttpBinding

wsHttpBinding

一个安全的通用的binding,但它不能在deplex中使用

WSDualHttpBinding

wsDualHttpBinding

一个安全的通用的binding,但能在deplex中使用

WSFederationHttpBinding

wsFederationHttpBinding

一个安全的通用的支持WSF的binding,能对用户进行验证和授权

NetTcpBinding

netTcpBinding

在wcf应用程序中最适合跨机器进行安全通讯的binding

NetNamedPipeBinding

netNamedPipeBinding

在wcf应用程序中最适合本机进行安全通讯的binding

NetMsmqBinding

netMsmqBinding

在wcf应用程序中最适合跨机器进行安全通讯的binding,并且支持排队

NetPeerTcpBinding

netPeerTcpBinding

一个支持安全的,多机交互的binding

msmqIntegrationBinding

下载源码地址:http://download.csdn.net/detail/ffuqiaoq/8537793

WCF入门及在WinForm中动态调用的更多相关文章

  1. Celery 分布式任务队列快速入门 以及在Django中动态添加定时任务

    Celery 分布式任务队列快速入门 以及在Django中动态添加定时任务 转自 金角大王 http://www.cnblogs.com/alex3714/articles/6351797.html ...

  2. 在C#环境中动态调用IronPython脚本(一)

    本文讲述用C#调用Ironpython运行环境,解析并运行动态pyhton脚本.这种情况应用在那些需要滞后规定行为的场合,例如,动态计算项(计算引擎),用户可以自定义计算内容.计算公式等. 本文的代码 ...

  3. C# 中静态调用C++dll 和C# 中动态调用C++dll

    在最近的项目中,牵涉到项目源代码保密问题,由于代码是C#写的,容易被反编译,因此决定抽取核心算法部分使用C++编写,C++到目前为止好像还不能被很好的反编译,当然如果你是反汇编高手的话,也许还是有可能 ...

  4. C#中动态调用DLL动态链接库

    其中要使用两个未公开的Win32 API函数来存取控制台窗口,这就需要使用动态调用的方法,动态调用中使用的Windows API函数主要有三个,即:Loadlibrary,GetProcAddress ...

  5. C#中动态调用DLL动态链接库(转)

    本来是想实现控制台程序运行时自动全屏,但是只找到VC下的实现方法(http://www.vckbase.com/bbs/prime/viewprime.asp?id=347). 其中要使用两个未公开的 ...

  6. WinForm中动态添加控件 出现事件混乱,解决办法记录。

    还是在抢票软件中出的问题,我没点击一个联系人,要生成一排控件,其中有席别combobox这样的下拉框控件,会出现如下图所示的问题:问题描述:在代码中动态创建的控件,事件混乱了,一个控件触发了所有同类型 ...

  7. 在C#中动态调用webService

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.W ...

  8. 在C#环境中动态调用IronPython脚本(二)

    一.Python数据类型与C#数据类型的对应 Python中数据类型中的简单类型,例如int,float,string可以对应到C#环境中的int32,double,string,这些对应比较直观,P ...

  9. winform中动态生成多行label,同时添加滚动条

    设计思路大概是这样的,Form内添加一个groupBox,groupBox内添加一个panel,panel的属性AutoScroll=true,在panel内动态添加label. 原始From如下: ...

随机推荐

  1. Visual Studio的.NET内存分配分析器解析

    Visual Studio 2012拥有丰富的有价值的功能,以至于我听到开发者反馈的需要的新功能新版本已经有了.另外,我听到开发人员询问具体的功能的某个特性,实际上他真正需要的是另外一个功能点. 上面 ...

  2. lua 中pairs 和 ipairs区别

    lua 中pairs 和 ipairs区别 标准库提供了集中迭代器,包括迭代文件每行的(io.lines),迭代table元素的(pairs),迭代数组元素的(ipairs),迭代字符串中单词的 (s ...

  3. JQuery Dialog 禁用X按钮关闭对话框,-摘自网络

    JQuery Dialog 禁用X按钮关闭对话框,禁用ESC键关闭代码如下:$("#div1").dialog({   closeOnEscape: false,   open: ...

  4. 数据中心基础设施自动化运维之puppet专项

    http://forge.puppetlabs.com/treydock/yum_cron  [puppet功能扩展forge] http://docs.puppetlabs.com/referenc ...

  5. 通过一张简单的图,让你彻底地搞懂JS的==运算

    大家知道,JavaScript中的==是一种比较复杂运算,它的运算规则很奇怪,很容易让人犯错,从而成为JavaScript中“最糟糕的特性”之一. 在仔细阅读ECMAScript规范的基础上,我画了一 ...

  6. 全英文版时间格式化07/29/2010 4:14:01 PM

    之前格式化,AM PM出不来,总是显示上午 下午 aspx页面的绑定: <%#Eval("AddDate") == DBNull.Value ? "" : ...

  7. 浅谈js单例模式

    单例模式就是在系统中保存一个实例,就是一个全局变量,在团队开发中,为了实现一些相似的功能,比如不同页面之间的表单验证,可能需求是不一样的,但是呢命名可能一样,这时就会产生冲突,这时候单例模式就能很好的 ...

  8. WEB API 用MemoryStream流做下载功能

    刚开始把MemoryStream 放在 var streamResult = new MemoryStream(); HttpResponseMessage response = new HttpRe ...

  9. C++/C#/java开发支持求解

    本人大一学C语言,大二学VB,大三学VC,毕业后工作前两年用C++,接着两年用C#,最近几个月Android开发用Java. 以下本人总结以下,有些疑惑希望大师帮忙解答. 1. C语言,精简,灵活,适 ...

  10. IOS7 自定义UIBarButtonItem 的一些问题

    ios 下自定义导航栏的BarButtonItem 会产生一些偏移问题, 解决方案: 通过新建一个系统的带固定距离的Item来调节你的Item #define   IOS7_NAVI_SPACE   ...