在net.tcp模式下,由SvcUtil.exe生成代理類文件和配置文件


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.cs
E:\WCF\WCF_ChatRoom\output.config
請按任意鍵繼續. . .

然后生成的文件為:ChatService.cs和output.config,內容如下:

ChatService.cs

View Code
//------------------------------------------------------------------------------
// <auto-generated>
//     此代碼由工具生成。
//     運行時版本:2.0.50727.5456
//
//     對此文件的更改可能會導致不正確的行為,並且如果
//     重新生成代碼,這些更改將會丟失。
// </auto-generated>
//------------------------------------------------------------------------------



[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="IChat", CallbackContract=typeof(IChatCallback), SessionMode=System.ServiceModel.SessionMode.Required)]
public interface IChat
{
    
    [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IChat/Join", ReplyAction="http://tempuri.org/IChat/JoinResponse")]
    string[] Join(string name);
    
    [System.ServiceModel.OperationContractAttribute(IsOneWay=true, IsInitiating=false, Action="http://tempuri.org/IChat/Say")]
    void Say(string msg);
    
    [System.ServiceModel.OperationContractAttribute(IsOneWay=true, IsInitiating=false, Action="http://tempuri.org/IChat/Whisper")]
    void Whisper(string to, string msg);
    
    [System.ServiceModel.OperationContractAttribute(IsOneWay=true, IsTerminating=true, IsInitiating=false, Action="http://tempuri.org/IChat/Leave")]
    void Leave();
}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public interface IChatCallback
{
    
    [System.ServiceModel.OperationContractAttribute(IsOneWay=true, Action="http://tempuri.org/IChat/Receive")]
    void Receive(string senderName, string message);
    
    [System.ServiceModel.OperationContractAttribute(IsOneWay=true, Action="http://tempuri.org/IChat/ReceiveWhisper")]
    void ReceiveWhisper(string senderName, string message);
    
    [System.ServiceModel.OperationContractAttribute(IsOneWay=true, Action="http://tempuri.org/IChat/UserEnter")]
    void UserEnter(string name);
    
    [System.ServiceModel.OperationContractAttribute(IsOneWay=true, Action="http://tempuri.org/IChat/UserLeave")]
    void UserLeave(string name);
}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public interface IChatChannel : IChat, System.ServiceModel.IClientChannel
{
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class ChatClient : System.ServiceModel.DuplexClientBase<IChat>, IChat
{
    
    public ChatClient(System.ServiceModel.InstanceContext callbackInstance) : 
            base(callbackInstance)
    {
    }
    
    public ChatClient(System.ServiceModel.InstanceContext callbackInstance, string endpointConfigurationName) : 
            base(callbackInstance, endpointConfigurationName)
    {
    }
    
    public ChatClient(System.ServiceModel.InstanceContext callbackInstance, string endpointConfigurationName, string remoteAddress) : 
            base(callbackInstance, endpointConfigurationName, remoteAddress)
    {
    }
    
    public ChatClient(System.ServiceModel.InstanceContext callbackInstance, string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(callbackInstance, endpointConfigurationName, remoteAddress)
    {
    }
    
    public ChatClient(System.ServiceModel.InstanceContext callbackInstance, System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(callbackInstance, binding, remoteAddress)
    {
    }
    
    public string[] Join(string name)
    {
        return base.Channel.Join(name);
    }
    
    public void Say(string msg)
    {
        base.Channel.Say(msg);
    }
    
    public void Whisper(string to, string msg)
    {
        base.Channel.Whisper(to, msg);
    }
    
    public void Leave()
    {
        base.Channel.Leave();
    }
}

output.config:

View Code
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>
        <bindings>
            <netTcpBinding>
                <binding name="NetTcpBinding_IChat" closeTimeout="00:01:00" openTimeout="00:01:00"
                    receiveTimeout="00:10:00" sendTimeout="00:01:00" transactionFlow="false"
                    transferMode="Buffered" transactionProtocol="OleTransactions"
                    hostNameComparisonMode="StrongWildcard" listenBacklog="10"
                    maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
                    maxReceivedMessageSize="65536">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="true" />
                    <security mode="None">
                        <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
                        <message clientCredentialType="Windows" />
                    </security>
                </binding>
            </netTcpBinding>
        </bindings>
        <client>
            <endpoint address="net.tcp://localhost:22222/chatservice" binding="netTcpBinding"
                bindingConfiguration="NetTcpBinding_IChat" contract="IChat"
                name="NetTcpBinding_IChat" />
        </client>
    </system.serviceModel>
</configuration>

然后將ChatService.cs放入客戶端的工程文件中,output.config改名為App.config,放到服務器端的工程文件中即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM