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, , 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 = ;
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 = "";//服务名字
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

浅谈辄止WCF:完成最基本的WCF项目(1)的更多相关文章

  1. 浅谈WebService的版本兼容性设计

    在现在大型的项目或者软件开发中,一般都会有很多种终端, PC端比如Winform.WebForm,移动端,比如各种Native客户端(iOS, Android, WP),Html5等,我们要满足以上所 ...

  2. 浅谈线程池(中):独立线程池的作用及IO线程池

    原文地址:http://blog.zhaojie.me/2009/07/thread-pool-2-dedicate-pool-and-io-pool.html 在上一篇文章中,我们简单讨论了线程池的 ...

  3. 浅谈 Fragment 生命周期

    版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 源码:AndroidDemo/Fragment 文中如有纰漏,欢迎大家留言指出. Fragment 是在 Android 3.0 中 ...

  4. 浅谈 LayoutInflater

    浅谈 LayoutInflater 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 源码:AndroidDemo/View 文中如有纰漏,欢迎大家留言指出. 在 Android 的 ...

  5. 浅谈Java的throw与throws

    转载:http://blog.csdn.net/luoweifu/article/details/10721543 我进行了一些加工,不是本人原创但比原博主要更完善~ 浅谈Java异常 以前虽然知道一 ...

  6. 浅谈SQL注入风险 - 一个Login拿下Server

    前两天,带着学生们学习了简单的ASP.NET MVC,通过ADO.NET方式连接数据库,实现增删改查. 可能有一部分学生提前预习过,在我写登录SQL的时候,他们鄙视我说:“老师你这SQL有注入,随便都 ...

  7. 浅谈angular2+ionic2

    浅谈angular2+ionic2   前言: 不要用angular的语法去写angular2,有人说二者就像Java和JavaScript的区别.   1. 项目所用:angular2+ionic2 ...

  8. iOS开发之浅谈MVVM的架构设计与团队协作

    今天写这篇博客是想达到抛砖引玉的作用,想与大家交流一下思想,相互学习,博文中有不足之处还望大家批评指正.本篇博客的内容沿袭以往博客的风格,也是以干货为主,偶尔扯扯咸蛋(哈哈~不好好工作又开始发表博客啦 ...

  9. Linux特殊符号浅谈

    Linux特殊字符浅谈 我们经常跟键盘上面那些特殊符号比如(?.!.~...)打交道,其实在Linux有其独特的含义,大致可以分为三类:Linux特殊符号.通配符.正则表达式. Linux特殊符号又可 ...

随机推荐

  1. 使用CodeMaid自动程序排版[转]

    前言 「使用StyleCop验证命名规则」这篇文章,指引开发人员透过StyleCop这个工具,来自动检验项目中产出的程序代码是否合乎命名规则. [Tool] 使用StyleCop验证命名规则 但是在项 ...

  2. 数组Byte [] 和 string 相互转换

    using System; using System.Collections.Generic; using System.Text; namespace NET.MST.Fourth.StringBy ...

  3. laravel中chunk方法使用外部变量以及改变该变量

  4. 阿里 RPC 框架 DUBBO 初体验

    最近研究了一下阿里开源的分布式RPC框架dubbo,楼主写了一个 demo,体验了一下dubbo的功能. 快速开始 实际上,dubbo的官方文档已经提供了如何使用这个RPC框架example代码,基于 ...

  5. Jquery Plugins Jquery Validate

      Jquery Validate 一.什么是Jquery Validate: jQuery Validate 插件为表单提供了强大的验证功能. 二.常用值: 1 required:true 必须输入 ...

  6. 【连载】redis库存操作,分布式锁的四种实现方式[四]--基于Redis lua脚本机制实现分布式锁

    一.redis lua介绍 Redis 提供了非常丰富的指令集,但是用户依然不满足,希望可以自定义扩充若干指令来完成一些特定领域的问题.Redis 为这样的用户场景提供了 lua 脚本支持,用户可以向 ...

  7. 「BZOJ 2342」「SHOI 2011」双倍回文「Manacher」

    题意 记\(s_R\)为\(s\)翻转后的串,求一个串最长的形如\(ss_Rss_R\)的子串长度 题解 这有一个复杂度明显\(O(n)\)的做法,思路来自网上某篇博客 一个双倍回文串肯定当且仅当本身 ...

  8. char *p="abc" 与 char p[]="abc" 的区别

    本文来源于网络 出处:点我 有这样一段代码: #include "stdio.h" char *get_string_1() { char p[] = "hello wo ...

  9. 51nod1258 序列求和 V4(伯努利数+多项式求逆)

    题面 传送门 题解 不知道伯努利数是什么的可以先去看看这篇文章 多项式求逆预处理伯努利数就行 因为这里模数感人,所以得用\(MTT\) //minamoto #include<bits/stdc ...

  10. lamp centos下一键安装

    系统需求 系统支持:CentOS 6+/Debian 7+/Ubuntu 12+ 内存要求:≥ 512MB 硬盘要求:至少 5GB 以上的剩余空间 服务器必须配置好 软件源 和 可连接外网 必须具有系 ...