WCF客户困惑

时间:2020-06-19 03:27:24

标签: c# .net wcf

我正在尝试连接到作为Windows服务托管的WCF服务。

WCF服务的端点位于:

net.tcp://localhost:9164/GettingStarted/

我可以正常启动服务。

但是,我现在正尝试通过控制台应用程序连接到它。

这是代码:

static void Main(string[] args)
{

    // Step 1: Create a URI to serve as the base address.
    Uri baseAddress = new Uri("net.tcp://localhost:9164/GettingStarted/");

    // Step 2: Create a ServiceHost instance.
    ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

    try
    {
        // Step 3: Add a service endpoint.
        selfHost.AddServiceEndpoint(typeof(ICalculator), new NetTcpBinding(), "CalculatorService");

        // Step 4: Enable metadata exchange.
        ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
        smb.HttpGetEnabled = false;
        smb.HttpsGetEnabled = false;
        selfHost.Description.Behaviors.Add(smb);

        // Step 5: Start the service.
        selfHost.Open();
        Console.WriteLine("The service is ready.");

        // Close the ServiceHost to stop the service.
        Console.WriteLine("Press <Enter> to terminate the service.");
        Console.WriteLine();
        Console.ReadLine();
        selfHost.Close();
    }
    catch (CommunicationException ce)
    {
        Console.WriteLine("An exception occurred: {0}", ce.Message);
        selfHost.Abort();
    }
}

运行此命令时,我不断收到此异常:

System.ServiceModel.AddressAlreadyInUseException

但是,没有其他东西连接到该服务。

此外,当基于http的时候,我可以通过Web浏览器测试该服务。如何使用net.tcp进行测试?

编辑:

WCF客户端更新:

static void Main(string[] args)
{
    ChannelFactory<ICalculator> channelFactory = null;

    try
    {
        NetTcpBinding binding = new NetTcpBinding();

        EndpointAddress endpointAddress = new EndpointAddress("net.tcp://localhost:9164/GettingStarted/CalculatorService");

        channelFactory = new ChannelFactory<ICalculator>(binding, endpointAddress);

        ICalculator channel = channelFactory.CreateChannel();

        double result = channel.Add(4.0, 5.9);
    }
    catch (TimeoutException)
    {
        //Timeout error  
        if (channelFactory != null)
            channelFactory.Abort();
        throw;
    }
    catch (FaultException)
    {
        if (channelFactory != null)
            channelFactory.Abort();
        throw;
    }
    catch (CommunicationException)
    {
        //Communication error  
        if (channelFactory != null)
            channelFactory.Abort();
        throw;
    }
    catch (Exception)
    {
        if (channelFactory != null)
            channelFactory.Abort();
        throw;
    }

}

1 个答案:

答案 0 :(得分:0)

根据您的描述,您的WCF服务已托管在Windows服务上。现在,您想连接到它。我不明白连接的含义。由于WCF服务托管在Windows服务上,因此您可以根据WCF服务生成一个代理类来调用它,但是我发现您的控制台应用程序仍然希望托管WCF服务。我不知道要做什么,但是如果要在控制台应用程序中托管WCF服务,则需要更改基地址,因为根据您的描述,您需要在Windows服务和控制台应用程序中托管WCF服务。但是它们的地址不能相同,您可以在控制台应用程序中更改基址,例如:

Uri baseAddress = new Uri("net.tcp://localhost:9166/Test/");
ServiceHost selfHost = new ServiceHost(typeof(Service1), baseAddress);