閱讀562 返回首頁    go 阿裏雲 go 技術社區[雲棲]


WCF概要

WCF:Windows Communication Foundation

一、特點概述:

1.統一ASMX, .NET Remoting, 與EnterpriseServices的開發模型:①為各種應用提供單一的編程模型;②基於配置驅動的協議選擇,消息格式,進程分配等等

2.麵向服務:①構建麵向服務的係統設計② 簡化實現SOA的方法

3.鬆耦合:①並沒有限製在特定的協議,編碼格式,或者主機環境上②所有的選項都可配置

4.可交互:支持Web Services的核心標準

5.已經批準和還未被批準的內容:在可擴展性方麵能夠快速適用新的協議和更新

6.整合性: 整合Microsoft早期的技術如:COM, Enterprise Services, MSMQ

二、原理示意圖:


實現代碼:

代碼結構


簡單的業務邏輯類:HelloIndigoService.cs

using System;
using System.ServiceModel;

namespace HelloIndigo
{
    [ServiceContract(Namespace="https://www.monkeyfu.net")]
    public interface IHelloIndigoService
    {
        [OperationContract]
        string HelloIndigo(string message);
    }

    public class HelloIndigoService : IHelloIndigoService
    { 
        #region IHelloIndigoService Members 
        public string HelloIndigo(string message)
        {
            return string.Format("Receivied message at{0}:{1}", DateTime.Now, message);
        } 
        #endregion
    }
} 

服務端:

using System;
using System.Collections.Generic;
using System.Text; 

//WCF使用到的命名空間
using System.ServiceModel;
using System.ServiceModel.Dispatcher;

namespace Host
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(HelloIndigo.HelloIndigoService)))
            {
                host.AddServiceEndpoint(typeof(HelloIndigo.IHelloIndigoService), new NetTcpBinding(), "net.tcp://localhost:9000/HelloIndigo");
                host.Open();
                Console.ReadLine();
            }
        }
    }
}

客戶端:

using System;
using System.Collections.Generic;
using System.Text;

using System.ServiceModel;
using Client.localhost;


namespace Client
{
    [ServiceContract(Namespace = "https://www.monkeyfu.net")]
    public interface IHelloIndigoService
    {
        [OperationContract]
        string HelloIndigo(string message);
    }

    class Program
    {
        static void Main(string[] args)
        {
             IHelloIndigoService proxy = ChannelFactory<IHelloIndigoService>.CreateChannel(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:9000/HelloIndigo"));
             string s = proxy.HelloIndigo("Hello from client...");
            Console.WriteLine(s);
            Console.ReadLine();
        }
    }
}

原理概述:客戶端和服務器端保存相同的接口(契約),至於這個契約可以由服務器端直接發布為服務,這個需要在Config裏進行配置:

 <endpoint binding="mexHttpBinding" contract="IMetadataExchange" address="mex"/>


最後更新:2017-04-02 06:51:45

  上一篇:go Android 程序的安裝、卸載和更新
  下一篇:go 關於java性能的小筆記