首页 > 解决方案 > 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;
    }

}

标签: c#.netwcf

解决方案


根据您的描述,您的 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);

推荐阅读