一、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. javaNIO(转载)

    (一) Java NIO 概述 Java NIO 由以下几个核心部分组成: Channels Buffers Selectors 虽然Java NIO 中除此之外还有很多类和组件,但在我看来,Chan ...

  2. vijosP1210 盒子与球

    vijosP1210 盒子与球 链接:https://vijos.org/p/1210 [思路] Stirling+全排列. 因为第二类stirling所求是没有标明盒子顺序的方案数,所以最后需要乘一 ...

  3. sed写的命令收集

    1. 替换一行字符串. <title name= > <param name="root", value="haha"/> <pa ...

  4. 问题-Delphi不能进行调试模式

    问题现象:delphi不能进行调试模式 问题原因:可能是防火墙的原因,我有一次在电脑清理时,把delphi的调试程序名放在了360的黑名单中,按F9后,无法调试. 问题处理:你懂的(要不白名单,要不你 ...

  5. Camtasia Studio8使用教程

    tip:善于使用ctrl+f搜索目录查看内容 目录 软件的下载与安装 软件的汉化与界面介绍 录制前准备与试机录制 录像机的设置 屏幕画 导入与编辑视频(包括图片,音乐,媒体) 时间线轨道时间轴 标记的 ...

  6. Objective-C 编程艺术 (Zen and the Art of the Objective-C Craftsmanship 中文翻译)

    # 禅与 Objective-C 编程艺术 (Zen and the Art of the Objective-C Craftsmanship 中文翻译) - 原文 <https://githu ...

  7. Java通过JDBC连接Oracle之后查询结果和在sqlplus查询结果不一样

    问题描述: 在sqlplus 下 orcl数据库中创建一张表后,使用insert语句插入几条数据 然后用java查询数据,发现在终端中输出的结果和在sqlplus中查询结果不一样. 在sqlplus中 ...

  8. IOS程序内发短信 MFMessageComposeViewController

    文章转载地址:http://www.headsky.org/?p=63 iOS4.0新加入了MFMessageComposeViewController和MFMessageComposeViewCon ...

  9. Wpf OpenFileDialog

                      Microsoft.Win32.OpenFileDialog openFileDialog1 = new Microsoft.Win32.OpenFileDialo ...

  10. c# 判断网络是连接到互联网

    方法1:InternetGetConnectedState         [System.Runtime.InteropServices.DllImport("wininet") ...