内射老阿姨1区2区3区4区_久久精品人人做人人爽电影蜜月_久久国产精品亚洲77777_99精品又大又爽又粗少妇毛片

wcf如何實(shí)現(xiàn)計(jì)算器功能

這篇文章主要介紹wcf如何實(shí)現(xiàn)計(jì)算器功能,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

創(chuàng)新互聯(lián)公司主要為客戶提供服務(wù)項(xiàng)目涵蓋了網(wǎng)頁視覺設(shè)計(jì)、VI標(biāo)志設(shè)計(jì)、營銷網(wǎng)站、網(wǎng)站程序開發(fā)、HTML5響應(yīng)式成都網(wǎng)站建設(shè)、成都做手機(jī)網(wǎng)站、微商城、網(wǎng)站托管及網(wǎng)站維護(hù)公司、WEB系統(tǒng)開發(fā)、域名注冊、國內(nèi)外服務(wù)器租用、視頻、平面設(shè)計(jì)、SEO優(yōu)化排名。設(shè)計(jì)、前端、后端三個(gè)建站步驟的完善服務(wù)體系。一人跟蹤測試的建站服務(wù)標(biāo)準(zhǔn)。已經(jīng)為成都宣傳片制作行業(yè)客戶提供了網(wǎng)站推廣服務(wù)。

WCF本質(zhì)上提供一個(gè)跨進(jìn)程、跨機(jī)器以致跨網(wǎng)絡(luò)的服務(wù)調(diào)用 ,本示例中 主要實(shí)現(xiàn)了計(jì)算器的功能,大部分的函數(shù)來源于網(wǎng)上別人的帖子,這叫站在巨人的肩膀上,O(∩_∩)O哈哈~,但是為了加深自己的對(duì)wcf的理解,因此決定自己在寫個(gè)類似的demo,把寫demo中遇到的問題展現(xiàn)出來,我相信對(duì)于初識(shí)wcf的程序員了來說,也會(huì)遇到各種問題。好了步入正題。

WCF 分為四個(gè)部分 1、契約(Interface)2、服務(wù)契約(Service)3、WCF 宿主程序(控制臺(tái)或者IIS) 4、客戶端(Client)

本人在寫wcf的時(shí)候喜歡將四個(gè)部分分別拆分成不同的類庫來管理。

1、契約

契約是對(duì)外開放的接口,暴露給客戶端的函數(shù)名稱首先,新建一個(gè)wcf服務(wù)庫,名稱為Interface,如圖所示:

wcf如何實(shí)現(xiàn)計(jì)算器功能

刪掉程序中默認(rèn)的文件(App.config,IService1.cs,Service1.cs),新建ICalculator

namespace Interface
{
    [ServiceContract(Name = "CalculatorService", Namespace = "")]public interface ICalculator
    {
        [OperationContract]double Add(double x, double y);

        [OperationContract]double Subtract(double x, double y);

        [OperationContract]double Multiply(double x, double y);

        [OperationContract]double Divide(double x, double y);

    }
}

2、新建服務(wù)契約,其實(shí)就是實(shí)現(xiàn)契約的類 ,添加"新建項(xiàng)目"->WCF->"WCF服務(wù)庫" (如 第一步新建契約是一樣的步驟),類庫的名稱為Service,

wcf如何實(shí)現(xiàn)計(jì)算器功能

新建成功后,刪除默認(rèn)文件(App.config,IService1.cs,Service1.cs),添加引用"Interface" 類庫,新建CalculatorService 并實(shí)現(xiàn)ICalculator

namespace Service
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]public class CalculatorService : ICalculator
    {public double Add(double x, double y)
        {return x + y;
        }public double Subtract(double x, double y)
        {return x - y;
        }public double Multiply(double x, double y)
        {return x * y;
        }public double Divide(double x, double y)
        {return x / y;
        }
    }

3、新建WCF宿主程序,WCF的契約和服務(wù)契約都已經(jīng)建完,但是還需要一個(gè)程序來承載這些接口供外部程序調(diào)用,因此稱之為宿主程序,宿主程序可以部署在IIS上,也可以用控制臺(tái)程序運(yùn)行方便調(diào)試,下面我就介紹用控制臺(tái)程序作為宿主程序。在解決方案的名稱右鍵添加"控制臺(tái)程序" 名稱為Hosting ,添加對(duì)Interface和Service的引用

實(shí)現(xiàn)wcf對(duì)外開放有兩種方式,一種方式是配置文件,將所有的WCF信息都寫到配置文件中

第一種:WCF的相關(guān)信息寫到配置文件(App.config)中

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
  </startup>
  <system.serviceModel>
    <services>
      <service name="Service.CalculatorService" behaviorConfiguration="WCFService.WCFServiceBehavior">
        <endpoint address="http://127.0.0.1:8888/CalculatorService" binding="wsHttpBinding" contract="Service.Interface.ICalculator">          
        </endpoint>
        <endpoint address="net.tcp://127.0.0.1:9999/CalculatorService"  binding="netTcpBinding"  contract="Service.Interface.ICalculator">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://127.0.0.1:8888/"/>
            <add baseAddress="net.tcp://127.0.0.1:9999/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WCFService.WCFServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Main方法的主要代碼如下,

    public class Program
    {internal static ServiceHost host = null;static void Main(string[] args)
        {using (ServiceHost host = new ServiceHost(typeof(CalculatorService)))
            {

                host.Opened += delegate{
                    Console.WriteLine("CalculaorService已經(jīng)啟動(dòng),按任意鍵終止服務(wù)!");
                };
                host.Open();
                Console.ReadLine();
            }
        }
    }

運(yùn)行控制臺(tái)程序,如下圖所示:

wcf如何實(shí)現(xiàn)計(jì)算器功能

第二種:寫一個(gè)WCFHelper類,添加幫助類的時(shí)候,一定引用System.Runtime.Serialization ,并且刪掉App.config 對(duì)wcf的配置,否則會(huì)報(bào)錯(cuò)代碼如下:

 public static class WCFHelper
    {public static string IP { get; set; }public static int Port { get; set; }static WCFHelper()
        {try{
                IP = System.Environment.MachineName;// ConfigurationManager.AppSettings["ServiceIP"];//                Port = int.Parse(ConfigurationManager.AppSettings["ServicePort"]);
            }catch{

            }

            EndpointAddress.Add(BindingProtocol.Http, "http://{0}:{1}/{2}/{3}");
            EndpointAddress.Add(BindingProtocol.NetTcp, "net.tcp://{0}:{1}/{2}/{3}");//EndpointAddress.Add(BindingProtocol.NetMsmq, "net.msmq://{0}:{1}/" + schema + "/{2}");//EndpointAddress.Add(BindingProtocol.NetPipe, "net.pipe://{0}:{1}/" + schema + "/{2}");try{
                httpBinding = new BasicHttpBinding();
                httpBinding.MaxBufferSize = 200065536;
                httpBinding.MaxReceivedMessageSize = 200065536;
                httpBinding.CloseTimeout = new TimeSpan(0, 10, 0);
                httpBinding.OpenTimeout = new TimeSpan(0, 10, 0);
                httpBinding.ReceiveTimeout = new TimeSpan(0, 10, 0);
                httpBinding.SendTimeout = new TimeSpan(0, 1, 0);

                httpBinding.Security.Mode = BasicHttpSecurityMode.None;

                httpBinding.ReaderQuotas.MaxDepth = 64;
                httpBinding.ReaderQuotas.MaxStringContentLength = 2147483647;
                httpBinding.ReaderQuotas.MaxArrayLength = 16384;
                httpBinding.ReaderQuotas.MaxBytesPerRead = 4096;
                httpBinding.ReaderQuotas.MaxNameTableCharCount = 16384;
            }catch{
                httpBinding = new BasicHttpBinding();
            }try{
                tcpBinding = new NetTcpBinding();
                tcpBinding.CloseTimeout = new TimeSpan(0, 1, 0);
                tcpBinding.OpenTimeout = new TimeSpan(0, 1, 0);
                tcpBinding.ReceiveTimeout = new TimeSpan(0, 10, 0);
                tcpBinding.SendTimeout = new TimeSpan(0, 1, 0);
                tcpBinding.TransactionFlow = false;
                tcpBinding.TransferMode = TransferMode.Buffered;
                tcpBinding.TransactionProtocol = TransactionProtocol.OleTransactions;
                tcpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
                tcpBinding.ListenBacklog = 100000;
                tcpBinding.MaxBufferPoolSize = 524288;
                tcpBinding.MaxBufferSize = 200065536;
                tcpBinding.MaxConnections = 2000;
                tcpBinding.MaxReceivedMessageSize = 200065536;
                tcpBinding.PortSharingEnabled = true;

                tcpBinding.Security.Mode = SecurityMode.None;

                tcpBinding.ReaderQuotas.MaxDepth = 64;
                tcpBinding.ReaderQuotas.MaxStringContentLength = 2147483647;
                tcpBinding.ReaderQuotas.MaxArrayLength = 163840000;
                tcpBinding.ReaderQuotas.MaxBytesPerRead = 4096;
                tcpBinding.ReaderQuotas.MaxNameTableCharCount = 16384;

                tcpBinding.ReliableSession.Ordered = true;
                tcpBinding.ReliableSession.InactivityTimeout = new TimeSpan(0, 10, 0);
                tcpBinding.ReliableSession.Enabled = false;
            }catch{
                tcpBinding = new NetTcpBinding();
            }
        }private static BasicHttpBinding httpBinding;public static BasicHttpBinding HttpBinding
        {get{return httpBinding;
            }
        }private static NetTcpBinding tcpBinding;public static NetTcpBinding TcpBinding
        {get{return tcpBinding;
            }
        }public static EndpointAddress GetEndpointAddress(string ip, int port, string serviceSchema, string serviceName, BindingProtocol protocol)
        {string address = EndpointAddress[protocol];
            address = string.Format(address, ip, port, serviceSchema, serviceName);return new EndpointAddress(address);
        }public static EndpointAddress GetEndpointAddress(string serviceSchema, string serviceName, BindingProtocol protocol)
        {string address = EndpointAddress[protocol];
            address = string.Format(address, IP, Port, serviceSchema, serviceName);return new EndpointAddress(address);
        }public static Uri GetBaseAddress(string ip, int port, string serviceSchema, string serviceName, BindingProtocol protocol)
        {string address = EndpointAddress[protocol];

            address = string.Format(address, ip, port + 1, serviceSchema, serviceName);return new Uri(address);
        }public static Uri GetBaseAddress(string serviceSchema, string serviceName, BindingProtocol protocol)
        {string address = EndpointAddress[protocol];

            address = string.Format(address, IP, Port + 1, serviceSchema, serviceName);return new Uri(address);
        }private readonly static Dictionary<BindingProtocol, string> EndpointAddress = new Dictionary<BindingProtocol, string>();public enum BindingProtocol
        {
            Http = 1,
            NetTcp = 2,//NetPipe = 3,//NetMsmq = 4        }
    }

將 宿主程序中的main方法改成如下:

    static void Main(string[] args)
        {
            WCFHelper.IP = "127.0.0.10";
            WCFHelper.Port = 9999;

            Uri httpUri = WCFHelper.GetBaseAddress(WCFHelper.IP, WCFHelper.Port, "Calculator", "Inspect", WCFHelper.BindingProtocol.Http);using (ServiceHost host = new ServiceHost(typeof(CalculatorService), httpUri))
            {
                host.AddServiceEndpoint(typeof(ICalculator), WCFHelper.TcpBinding, WCFHelper.GetEndpointAddress(WCFHelper.IP, WCFHelper.Port, "Calculator", "InspectService", WCFHelper.BindingProtocol.NetTcp).Uri.AbsoluteUri);
                ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();#if DEBUGbehavior.HttpGetEnabled = true;#elsebehavior.HttpGetEnabled = false;#endifhost.Description.Behaviors.Add(behavior);
                host.Opened += delegate{
                    Console.WriteLine("CalculaorService已經(jīng)啟動(dòng),按任意鍵終止服務(wù)!");
                };
                host.Open();

                Console.ReadLine();
            }
}

4、宿主程序建完了,WCF的所有鍥約已經(jīng)對(duì)外可以訪問了,那現(xiàn)在需要建立Client 去調(diào)用wcf程序了 ,

首先,編譯宿主程序Host,找到bin/debug/ Host.exe 右鍵管理員打開,如果如下圖證明服務(wù)已經(jīng)于寧

wcf如何實(shí)現(xiàn)計(jì)算器功能

其次,在解決方案名稱->右鍵添加Winform程序 新建WinForm 程序,添加"服務(wù)引用"

添加服務(wù)引用 (此引用方式,是以"3、添加宿主程序" ->"第二種 WCF幫助類的方式")

wcf如何實(shí)現(xiàn)計(jì)算器功能

wcf如何實(shí)現(xiàn)計(jì)算器功能

點(diǎn)擊“轉(zhuǎn)到” 系統(tǒng)發(fā)現(xiàn)WCF服務(wù),如下圖所示:

wcf如何實(shí)現(xiàn)計(jì)算器功能

點(diǎn)擊確定,就成功的將wcf的引用了,下面開始調(diào)用WCF的程序了,例如調(diào)用Add方法,代碼如下:

 ServiceReference1.CalculatorServiceClient client = new ServiceReference1.CalculatorServiceClient();
            textBox3.Text = client.Add(double.Parse(textBox1.Text), double.Parse(textBox2.Text)).ToString();

到此為止,wcf程序已經(jīng)完成的跑通了,記得 調(diào)試的時(shí)候已經(jīng)把宿主程序和client程序同時(shí)運(yùn)行。

如果閑麻煩,vs 支持同時(shí)啟動(dòng)多個(gè)項(xiàng)目,可以同時(shí)把client 和host同時(shí)啟動(dòng)

wcf如何實(shí)現(xiàn)計(jì)算器功能

以上是wcf如何實(shí)現(xiàn)計(jì)算器功能的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

文章名稱:wcf如何實(shí)現(xiàn)計(jì)算器功能
網(wǎng)頁鏈接:http://www.rwnh.cn/article20/jisdjo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站收錄網(wǎng)站改版、品牌網(wǎng)站制作、網(wǎng)站制作云服務(wù)器、品牌網(wǎng)站設(shè)計(jì)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)
沂源县| 禹州市| 建昌县| 武山县| 湟中县| 岫岩| 永寿县| 界首市| 阿坝| 交城县| 应用必备| 绥德县| 浑源县| 六盘水市| 竹山县| 哈尔滨市| 嵊泗县| 莒南县| 常德市| 岗巴县| 乳源| 靖远县| 乐至县| 梅州市| 自治县| 湖州市| 松潘县| 稷山县| 曲阳县| 安新县| 舞钢市| 宜都市| 文安县| 马龙县| 同心县| 南宫市| 长春市| 湘阴县| 芜湖市| 枞阳县| 临沧市|