一、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. c++学习_2

    这里承接上一篇文章,继续记录关于继承的那些事儿... NVI(non-Virtual Interface)和strategy模式 NVI模式和strategy模式是两种不同的方法,可以用来替代virt ...

  2. POJ2752 - Seek the Name, Seek the Fame(KMP)

    题目大意 给定一个字符串S,求出所有既是S的前缀又是S的后缀的子串长度 题解 从末尾位置倒推,经过的失配函数值就是题目要求求的 代码: #include <iostream> #inclu ...

  3. 订阅基础:RSS、ATOM、FEED、聚合、供稿、合烧与订阅

    很多网友对这类名词概念非常陌生,如果没用过FEED订阅,肯定还会对诸多网站显示的FEED聚合.订阅.ATOM等等非常郁闷,虽然这几个名字间的很多并非并列关系,天缘只是有意把它们放到一起,方便对比参考, ...

  4. C# 基础知识 protected 关键字

    using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace Console ...

  5. excel重复数据

    =COUNTIF(H:H,H1)>1

  6. 各种会义PPT

    http://vdisk.weibo.com/s/dBzv2siaHK2H http://vdisk.weibo.com/wap/u/3460619722 https://yunqi.aliyun.c ...

  7. CLOSE_WAIT状态的原因与解决方法 --转

    转自:http://blog.chinaunix.net/uid-20357359-id-1963662.html 这个问题之前没有怎么留意过,是最近在面试过程中遇到的一个问题,面了两家公司,两家公司 ...

  8. 真相:中国版BBB用USB连电脑没有盘符的根本原因分析

    很多网友在问:为什么中国版的装完驱动插上板子没有显示端口号和69M的盘符??楼主发现,在开机启动的时候,加载g_multi模块时出现错误提示 invalid argument.         Emb ...

  9. java学习粗略路线

    首先是JAVA基础JAVA SE(用于开发和部署桌面.服务器以及嵌入设备和实时环境中的Java应用程序.) 之后是JAVA EE(java企业级标准开发),先学习Servlet(控制器).JSP(在h ...

  10. 监控Linux内存使用情况

    cat mem.sh#!/bin/bashIP=`ifconfig | grep 'inet ' | grep -v '127.0.0.1' | awk -F ' ' '{print $2}'| aw ...