一、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. NOIP2000 乘积最大

    题二  乘积最大              (22分)    问题描述      今年是国际数学联盟确定的“2000——世界数学年”,又恰逢我国著名数学家华罗庚先生诞辰90周年.在华罗庚先生的家乡江苏 ...

  2. A better way to learn D3 js - iLearning D3.js

    iLearning D3.js Basic is an iPad app to learn and code with D3. In 1.1 version, new tutorial is prov ...

  3. 各种sensor名称统计

    gyroscopes 陀螺仪accelerometers 加速度计magnetometers 磁力计barometric pressure 气压remote pressure sensing 远程压力 ...

  4. Spring笔记之(一)初探

    对spring框架的学习我是从模拟它的简单实现开始,这样也易于领悟到它的整个框架结构,以下是简单实现的代码: 配置文件:spring.xml <?xml version="1.0&qu ...

  5. HW4.37

    import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner i ...

  6. [Locked] Unique Word Abbreviation

    Unique Word Abbreviation An abbreviation of a word follows the form <first letter><number&g ...

  7. POJ2250 - Compromise(LCS+打印路径)

    题目大意 给定两段文本,问公共单词有多少个 题解 裸LCS... 代码: #include<iostream> #include<string> using namespace ...

  8. Replacing JNI Crashes by Exceptions on Android

    http://blog.httrack.com/blog/2013/08/23/catching-posix-signals-on-android/ To Report Or Not To Repor ...

  9. unexpected error ConnectionError object has no attribute

    unexpected error ConnectionError object has no attribute

  10. CentosX64使用yum快速搭建xen虚拟化环境

    Xen的大名想必已经被众SA所熟知.Xen 是一个开放源代码虚拟机监视器,由剑桥大学开发.它打算在单个计算机上运行多达100个满特征的操作系统.操作系统必须进行显式地修改(“移植”)以在Xen上运行( ...