浅谈辄止WCF:完成最基本的WCF项目(1)
Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台。
WCF的所有服务都会公开契约。契约包含以下四种类型
1.服务契约
2.数据契约
3.错误契约
4.消息契约
今天主要介绍服务契约实现WCF项目,服务契约描述了客户端能够执行的服务操作。
项目结构截图:
1.定义和实现服务契约
通过将ServiceContractAttribute属性标记到接口或者类型上。遵循了面向服务的原则,所有的契约必须要明确要求:只有接口和类可以标记为Servicecontract属性,从而为WCF服务,即便标记了ServiceContract属性,类的所有成员也不一定就是契约的一部分,我们必须使用OperationContract属性表明哪些方法需要暴露为WCF契约中的一部分。
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace WCFServiceHosting
{
[ServiceContract]//标记为服务,不标记则客户端无法访问
public interface IDataExChangeService
{
[OperationContract]
void ShowMsg(string str);
//不标记不会成为契约一部分
void ShowMsg1(string str);
}
}
需要一个类去实现这个接口,表明方法的实际作用,我们只需要去将暴露为服务的方法实现。这里只是简单的将传入的参数写入了文件
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace WCFServiceHosting
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class DataExChangeService : IDataExChangeService
{
private FileStream fs;
public void ShowMsg(string str)
{
fs = new FileStream("c://Warrenwell.log//log.txt",FileMode.Create,FileAccess.ReadWrite);
byte[] messages = System.Text.Encoding.Default.GetBytes(str);
fs.Write(messages, 0, messages.Length);
fs.Close();
}
public void ShowMsg1(string str)
{
throw new NotImplementedException();
}
}
}
2.托管
wcf服务不能凭空存在,每个服务都必须托管到windows进程中,该进程叫做宿主进程。
我们这里使用自托管,我们托管到windows窗体应用程序中,托管应用程序配置文件通常会列出所有希望托管和公开的服务类型
<services>
<service name="WCFServiceHosting.DataExChangeService">
<host>
<baseAddresses>
<add baseAddress="http://192.168.0.44:8002/ReceiveMessage/"/>
</baseAddresses>
</host>
<endpoint address="" binding="basicHttpBinding" contract="WCFServiceHosting.IDataExChangeService" />
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
</services>
在windows窗体应用程序中托管服务的代码为
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WCFServiceHosting
{
public partial class ServiceHostHandler:ServiceBase
{
private ServiceHost host;
private System.Timers.Timer timer = new System.Timers.Timer();
private const int timerInterval = 1000;
public ServiceHostHandler()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
if (host != null)
{
host.Close();
}
host = new ServiceHost(typeof(DataExChangeService));
host.Open();
timer.Interval = timerInterval;
timer.Start();
}
catch(Exception ex)
{
throw;
}
}
protected override void OnStop()
{
try
{
if (timer.Enabled)
{
timer.Close();
timer.Dispose();
}
if (host != null)
{
host.Close();
host = null;
}
}
catch (Exception ex)
{
throw;
}
}
}
}
最后在窗体程序的program.cs文件中设置为启动这个窗体程序,由于服务托管于此窗体程序中,所以相当于启动了服务
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WCFServiceHosting
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
ServiceBase[] serviceToRun;
serviceToRun = new ServiceBase[]
{
new ServiceHostHandler()
};
ServiceBase.Run(serviceToRun);
}
}
}
3.将程序做成服务安装到服务器中
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WCFServiceHosting
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
}
}
namespace WCFServiceHosting
{
partial class ProjectInstaller
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.serviceProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller
//
this.serviceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller.Password = null;
this.serviceProcessInstaller.Username = null;
//
// serviceInstaller
//
this.serviceInstaller.Description = "Exchange data with Hospital Information System.";
this.serviceInstaller.DisplayName = "123";//服务名字
this.serviceInstaller.ServiceName = "ReceiveMessage";
this.serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller,
this.serviceInstaller});
}
#endregion
private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller;
private System.ServiceProcess.ServiceInstaller serviceInstaller;
}
}
4.安装我们的WCF服务到服务器上
打开命令提示符,右击管理员身份运行,输入cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
继续输入InstallUtil.exe C:\Users\123\Documents\VisualStudio2017\Projects\P2P\WindowsFormsApp2\bin\Debug\WindowsFormsApp2.exe
由于我的服务已经存在了所以就提示我已经存在。
之后就能在计算机管理——服务里面看到我们的123服务了,打开123服务后,别人就能够调用了,关于调用方法,下章继续,拜拜=V=。
项目整体源码下载地址 http://download.csdn.net/download/china_zhangdapao/10255850