【发布时间】:2020-06-19 03:27:24
【问题描述】:
我正在尝试连接到作为 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;
}
}
【问题讨论】:
-
对不起,我很困惑。您为服务器(带有ServiceHost)而不是客户端显示的代码不是。自从我与 WCF 合作以来已经很长时间了,但我怀疑我忘记了那么多
-
没有?服务器端只是一个引用我的 WCF 服务库的 WCF 服务项目。这是一个尝试连接到它的客户端控制台项目。
-
对于局域网通信,您有 WCF 的替代方案吗?这令人非常沮丧。