WCF: Net.TCP multiple bindings, same port, different IP Addresses

后端 未结 3 390
暖寄归人
暖寄归人 2020-12-29 12:40

I\'ve run into a problem. I\'m a little new at WCF so any help would be greatly appreaciated.

Here\'s my code:

public static void StartHosts()
    {
         


        
3条回答
  •  生来不讨喜
    2020-12-29 13:15

    Thanks for the info Corazza!

    I've figured out how to accomplish this. I was going about this all the wrong way.

    My ultimate goal was to have the service listening on every IP Address available on the machine. Trying to bind to each address individually is the wrong way of doing this.

    Instead, I only needed to bind the service to the machine's Host Name (not 'localhost') and WCF automatically listens on all adapters.

    Here's the corrected code:

    public static void StartHosts()
        {
            try
            {
                // Formulate the uri for this host
                string uri = string.Format(
                    "net.tcp://{0}:{1}/ServerTasks",
                    Dns.GetHostName(),
                    ServerSettings.Instance.TCPListeningPort
                );
    
                // Create a new host
                ServiceHost host = new ServiceHost(typeof(ServerTasks), new Uri(uri));
    
                // Add the endpoint binding
                host.AddServiceEndpoint(
                    typeof(ServerTasks),
                    new NetTcpBinding(SecurityMode.Transport) 
                            { 
                                TransferMode = TransferMode.Streamed
                            },
                    uri
                );
    
                // Add the meta data publishing
                var smb = host.Description.Behaviors.Find();
                if (smb == null)
                    smb = new ServiceMetadataBehavior();
    
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);
    
                host.AddServiceEndpoint(
                    ServiceMetadataBehavior.MexContractName,
                    MetadataExchangeBindings.CreateMexTcpBinding(),
                    "net.tcp://localhost/ServerTasks/mex"
                );
    
                // Run the host
                host.Open();
            }
            catch (Exception exc)
            {
                DebugLogger.WriteException(exc);
            }
        }
    

提交回复
热议问题