標籤:des style blog http os 使用 io ar 檔案
WCF服務調用可以採用兩個方法,由工具SvcUtil.exe產生本地代理服務類和設定檔方式,或者採用ChannelFactory直接建立服務代理對象。本文主要採用前面一種方式來進行。
SvcUtil.exe位於:C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin目錄下,可以將本工具添加到VS2010的工具菜單中,以方便使用:
VS菜單-》工具-》外部工具-》添加-》在“命令”文字框選取其路徑如下:C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcUtil.exe,在初始目錄(這裡是設定檔和代理類產生後放置的地方),我們選取“$(SolutionDir)”。
添加完成後,工具下拉式功能表會出現SvcUtil,如何使用呢?
首先,對於Http類型的Uri來說,很容易搞定,直接在SvcUtil的輸入框輸入類似:http://localhost:22222/calService/metadata即可產生伺服器端在用戶端的代理類和設定檔,然後將這兩個檔案拷到項目中並將output.config改名為app.config就可以了。
如果遇到net.tcp(比如:net.tcp://localhost:22222/chatservice)該怎麼進行呢?
其實很簡單,我們只需要在服務入口處添加Service的EndPoint即可。
Uri uri = new Uri(ConfigurationManager.AppSettings["addr"]); using(ServiceHost host = new ServiceHost(typeof(NikeSoftChat.ChatService),uri)) { ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>(); if (smb == null) { host.Description.Behaviors.Add(new ServiceMetadataBehavior()); } host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); host.Open(); Console.WriteLine("Chat service listen on endpoint {0}", uri.ToString()); Console.WriteLine("Press ENTER to stop chat service..."); Console.ReadLine(); host.Abort(); host.Close(); }
注意,黃色標記很重要,它能夠暴露出中繼資料出來,如果沒有黃色標記部分,利用SvcUtil產生net.tcp的代理類和設定檔將是不可能的。
然後,將net.tcp://localhost:22222/chatservice輸入SvcUtil.exe的輸入框,然後點擊產生,顯示資訊如下:
Microsoft (R) Service Model Metadata Tool[Microsoft (R) Windows (R) Communication Foundation,版本 3.0.4506.2152]著作權(c) Microsoft Corporation。著作權所有,並保留一切權利。正在嘗試使用 WS-Metadata Exchange 從“net.tcp://localhost:22222/chatservice”下載中繼資料。此 URL 不支援 DISCO。正在組建檔案...E:\WCF\WCF_ChatRoom\ChatService.csE:\WCF\WCF_ChatRoom\output.config請按任意鍵繼續. . .
在net.tcp模式下,由SvcUtil.exe組建代理程式類檔案和設定檔(轉)