基于net.tcp的WCF配置实例解析(转)
http://www.cnblogs.com/scy251147/archive/2012/11/23/2784902.html 原文
本文主要通过文件配置来讲解如何编写一个基于net.tcp的Windows Form小程序。
涉及的工具有:
SvcUtil.exe
WCF Service Configuration Editor
服务器端的配置步骤
首先让我们来开始编写服务器端,服务器端用的是Console Application。
由于我们的软件是一个能够通过学生ID来获取学生姓名的小程序,所以,首先必须得有一个StudentInfo实体类:
using System.Runtime.Serialization; namespace WCFServiceGeneratedByConfig
{
[DataContract]
public class StudentInfo
{
int studentID; string lastName; string firstName; [DataMember]
public int StudentID
{
get { return studentID; }
set { studentID = value; }
} [DataMember]
public string FirstName
{
get { return firstName; }
set { firstName = value; }
} [DataMember]
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}
}
在这个实体类中,DataContract代表数据契约,DataMeber代表数据成员,加上这些Attribute后,能够传送给Client端。
然后是一个接口,这个接口定义了服务契约和操作契约:
using System.Collections.Generic; using System.ServiceModel; namespace WCFServiceGeneratedByConfig
{
[ServiceContract]
public interface IStudentService
{
[OperationContract]
string GetStudentFullName(int studentId); [OperationContract]
IEnumerable<StudentInfo> GetStudentInfo(int studentId);
}
}
using System.Collections.Generic;
using System.Linq; namespace WCFServiceGeneratedByConfig
{
public class StudentService : IStudentService
{
List<StudentInfo> list = new List<StudentInfo>(); public StudentService()
{
list.Add(new StudentInfo { StudentID = , FirstName = "Shi", LastName = "Chaoyang" });
list.Add(new StudentInfo { StudentID = , FirstName = "Liu", LastName = "Jieus" });
list.Add(new StudentInfo { StudentID = , FirstName = "Cheung", LastName = "Vincent" });
list.Add(new StudentInfo { StudentID = , FirstName = "Yang", LastName = "KaiVen" });
} public string GetStudentFullName(int studentId)
{
IEnumerable<string> Student = from p in list
where p.StudentID == studentId
select p.FirstName + " " + p.LastName;
return Student.Count() != ? Student.First() : string.Empty;
} public IEnumerable<StudentInfo> GetStudentInfo(int studentId)
{
IEnumerable<StudentInfo> Student = from p in list
where p.StudentID == studentId
select p;
return Student;
}
}
}
这个方法里,我们有两个函数,一个能够根据学生点获取学生全名,另一个是根据学生点获取学生的实体对象。
好了,让我们来编译这个项目,得到一个WCFServiceGeneratedByConfig.exe文件。
然后,我们需要配置文件来让服务器端启动,所以这里我们要用WCF Service Configuration Editor
工具来进行,由于在VS2008 和VS2010中带有这个软件,我们可以直接通过菜单->Tools->WCF Service Configuration Editor来打开。
首先,点击File->New config, 打开Service的Configuration界面。

然后,点击Create a new service…,在弹出的界面中,我们选择刚才生成的那个WCFServiceGeneratedByConfig.exe文件。双击之后,软件自动显示出了里面含有的Service:

点选那个Service,然后点击两次next,我们会看到出现了选择Communation Mode的界面,这里由于我们用的是net.tcp,所以我选择了第一个:TCP。

然后点击Next,我们会看到要我们填写EndPoint,这里我随便填写了一个:

之后,点击Next知道Finish,然后,我们的最基本的配置就结束了。
回到Config界面之后,我们点击Advanced->Service Behaviors->New Service Behavior Configuration,在弹出的界面中,我们点击Add->serviceMetadata:

然后点击Add,我们就添加了一个Behavior Element。点击刚刚生成的serviceMetadata节点,在显示的界面中,设置HttpGetEnabled为true。

然后点击原来的Service节点下的Host节点,在Base Address栏目下单击Add,添加如下的Base Address:

最后点击OK。然后点击菜单File->Save As 保存到项目文件夹下即可。
这里是生成的代码:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="StudentBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WCFServiceGeneratedByConfig.StudentService">
<endpoint address="net.tcp://127.0.0.1:50001/StudentServiceEndPoint"
binding="netTcpBinding" bindingConfiguration="" contract="WCFServiceGeneratedByConfig.IStudentService" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://127.0.0.1:50001/StudentServiceEndPoint" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
这一步做完后,我们需要让服务能够启动,怎么启动呢?请看下面的代码:
using System;
using System.ServiceModel;
using System.ServiceModel.Description; namespace WCFServiceGeneratedByConfig
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(StudentService)))
{
ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null)
host.Description.Behaviors.Add(new ServiceMetadataBehavior()); //暴露出元数据,以便能够让SvcUtil.exe自动生成配置文件
host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); //开启服务
host.Open();
Console.WriteLine("Service listen begin to listen...");
Console.WriteLine("press any key to teriminate...");
Console.ReadKey();
host.Abort();
host.Close();
}
}
}
}
代码中的注释部分非常重要,我们一定要添加,否则下面的步骤不能进行,具体的原因,参加我的另一篇文章:在net.tcp模式下,由SvcUtil.exe生成代理类文件和配置文件
然后运行这个ConsoleApplication。
接下来,找到SvcUtil.exe,C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcUtil.exe,在CMD窗口下运行如下命令:
C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcUtil.exe net.tcp://127.0.0.1:50001/StudentServiceEndPoint
这样,这个小工具就会自动的给我们生成代理类和配置文件
Microsoft (R) Service Model Metadata Tool [Microsoft (R) Windows (R) Communication Foundation,版本 3.0.4506.2152] 版权所有(c) Microsoft Corporation。保留所有权利。 正在尝试使用 WS-Metadata Exchange 从“net.tcp://127.0.0.1:50001/StudentServiceEndPoint”下载元数据。此 URL 不支持 DISCO。 正在生成文件... E:\WCF\WCF_ChatRoom\StudentService.cs E:\WCF\WCF_ChatRoom\output.config 请按任意键继续. . .
客户端的配置步骤
接下来,新建一个WindowsFormsApplication程序,将这个代理类拷入,配置文件修改名称为App.config拷入,
然后在Form1.cs中拖入一个文本框,一个按钮,一个DataGridView,后台代码如下:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using WCFServiceGeneratedByConfig; namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
Action action = new Action(Bind);
action.BeginInvoke(new AsyncCallback((iar) =>
{
Action actionEnd = (Action)iar.AsyncState;
actionEnd.EndInvoke(iar);
}), action);
} private void Bind()
{
StudentServiceClient client = new StudentServiceClient();
IEnumerable<StudentInfo> x = client.GetStudentInfo(Int32.Parse(textBox1.Text));
dataGridView1.Invoke((Action)(() => { dataGridView1.DataSource = x; }));
}
}
}
启动这个实例,输入学生ID,我们成功得到了服务端返回的值。

那么能不能在公网上使用呢?呵呵,这个当然,将服务端拷贝到外网的一台机器上,然后修改服务器端的配置文件中的地址为:net.tcp://169.*.*.124:50001/ StudentServiceEndPoint,然后将本机的配置文件中的地址也修改为这个,最后运行,依然能够得到返回的结果。
基于net.tcp的WCF配置实例解析(转)的更多相关文章
- WCF使用net.tcp绑定的配置实例
<system.serviceModel> <bindings> <basicHttpBinding> <!--默认http绑定的配置,这里提高了最大传输信息 ...
- SSO 基于Cookie+fliter实现单点登录 实例解析(一)
接上文,SSO的理论讲解,接下来实践实践! 1.使用Cookie解决单点登录 技术点: 1.设置Cookie的路径为setPath("/").即Tomcat的目录下都有效 2.设置 ...
- spring-mvc 3.* 多视图解析配置实例 ContentNegotiatingViewResolver
一.起因 从spring 3.1.0升级到spring 3.2.0时,配置文件servlet.xml中出错. 错误信息: java.lang.String cannot be cast to ...
- WCF配置详解
前面一篇文章<WCF 学习总结1 -- 简单实例> 一股脑儿展示了几种WCF部署方式,其中配置文件(App.config/Web.config)都是IDE自动生成,省去了我们不少功夫.现在 ...
- WCF中配置文件解析
WCF中配置文件解析[1] 2014-06-14 WCF中配置文件解析 参考 WCF中配置文件解析 返回 在WCF Service Configuration Editor的使用中,我们通过配置工具自 ...
- JavaWeb实现文件上传下载功能实例解析
转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web应用系统开发中,文件上传和下载功能是非常常用的功能 ...
- WCF分布式开发步步为赢(9):WCF服务实例激活类型编程与开发
.Net Remoting的激活方式也有三种:SingleTon模式.SingleCall模式.客户端激活方式,WCF服务实例激活类型包括三种方式:单调服务(Call Service),会话服务(Se ...
- WCF小实例以及三种宿主
WCF小实例以及三种宿主 最近一直在学习WCF相关知识,下面将通过一个小实例对所学的知识进行简单的回顾:本实例是一个简单三层操作数据库,并且也简单实现的三种宿主(控制台宿主,IIS宿主以及Window ...
- Tomcat配置实例
转自:https://www.cnblogs.com/kismetv/p/7228274.html 目录 一.一个server.xml配置实例 二.server.xml文档的元素分类和整体结构 1.整 ...
随机推荐
- 跨域通信--Window.postMessage()
一.跨源通信概述 源:协议.端口号(https默认值433).主机域名(document.domain) 作用:向目标窗口派发MessageEvent消息(四个属性) 兼容参考 MessageEven ...
- Java设计模式(7)装饰模式(Decorator模式)
Decorator常被翻译成"装饰",我觉得翻译成"油漆工"更形象点,油漆工(decorator)是用来刷油漆的,那么被刷油漆的对象我们称decoratee.这 ...
- C#中二进制和流之间的各种相互转换
一. 二进制转换成图片间的转换 1 2 3 4 5 MemoryStream ms = new MemoryStream(bytes); ms.Position = 0; Image img = Im ...
- ASP.NET中使用JavaScript实现图片自动水平滚动效果
参照网上的资料,在ASP.NET中使用JavaScript实现图片自动水平滚动效果. 1.页面前台代码: <%@ Page Language="C#" AutoEventWi ...
- Android中获取系统上安装的APP信息
Version:0.9 StartHTML:-1 EndHTML:-1 StartFragment:00000099 EndFragment:00003259 Android中获取系统上安装的APP信 ...
- android地址位置
有精度纬度确定地理位置 latitude: 23.1352888---longitude: 113.3297445 调用Google API接口: URL: http://maps.google.cn ...
- SNMP MIB库
-- mib文件的开头指定文件名,并且使用BEGIN开始,文件的最后用END结束 -- IMPORTS就相当与c语言中的include,包含需要使用的一些数据类型 -- 通过FROM指定引用的来源 M ...
- MySQL存储过程、触发器 小例子
一.存储过程 语法: CREATE PROCEDURE([[IN |OUT |INOUT ] 参数名 数据类形...]) BEGIN ... END 参数: IN 输入参数 表示该参数的值必须在调用存 ...
- Linux使用 tar命令-g参数进行增量+差异备份、还原文件
原文链接:http://www.cnblogs.com/gnuhpc/ 完整备份: 建立测试路径与档案 mkdir test touch test/{a,b,c} 在test下生成三个文件 执行完整备 ...
- FusionCancer-人类癌症相关的融合基因的数据库
RNA-seq 测序可以用于融合基因的发现,在过去的十几年里,RNA-seq 测序数据不断增加,发现的融合基因的数据也不断增加: FusionCancer 是一个人类癌症相关的融合基因的数据库,利用N ...