c# - 无法添加 net.tcp 作为服务引用

标签 c# wcf tcp metadata nettcpbinding

我创建了一个 net.tcp WCF 服务,如下所示:

const string tcpUri = "net.tcp://localhost:9038";
var netTcpHost = new WebServiceHost(typeof(DashboardService), new Uri(tcpUri));
netTcpHost.AddServiceEndpoint(typeof(IDashboardService), new NetTcpBinding(), 
                                                             "/dashboard");

netTcpHost.Open();

Console.WriteLine("Hosted at {0}. Hit any key to shut down", tcpUri);
Console.ReadKey();

netTcpHost.Close();

这是我的 IDashboardServiceDashboardSerivce 定义:

[ServiceContract]
public interface IDashboardService
{
    [OperationContract]
    PositionDashboard Loader();
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class DashboardService : IDashboardService
{
    public PositionDashboard Loader()
    {
        ...
    }
}

但是,当我尝试使用 WCF 测试客户端连接到服务时,出现以下错误:

Error: Cannot obtain Metadata from net.tcp://localhost:9038/dashboard
The socket connection was aborted. This could be caused by an error processing your 
message or a receive timeout being exceeded by the remote host, or an underlying 
network resource issue. Local socket timeout was '00:04:59.9890000'.    An existing 
connection was forcibly closed by the remote host

最佳答案

该错误明确提及“无法获取元数据...”,因此值得检查您是否具有 TCP Mex 端点。它在配置中应该看起来像这样:

<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" />

或者,如果您想这样做,则需要引用 System.ServiceModel.Discovery,然后您的代码应如下所示:

const string tcpUri = "net.tcp://localhost:9038";
using (var netTcpHost = new WebServiceHost(
    typeof(DashboardService),
    new Uri(tcpUri)))
{
    netTcpHost.Description.Behaviors.Add(new ServiceMetadataBehavior());
    netTcpHost.AddServiceEndpoint(
        typeof(IMetadataExchange),
        MetadataExchangeBindings.CreateMexTcpBinding(),
        "mex");
    netTcpHost.AddServiceEndpoint(
        typeof(IDashboardService),
        new NetTcpBinding(),
        "dashboard");

    netTcpHost.Description.Behaviors.Add(new ServiceDiscoveryBehavior());
    netTcpHost.AddServiceEndpoint(new UdpDiscoveryEndpoint());

    netTcpHost.Open();
    Console.WriteLine("Hosted at {0}. Hit any key to shut down", tcpUri);
    Console.ReadLine();

    netTcpHost.Close();
}

关于c# - 无法添加 net.tcp 作为服务引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24937389/

相关文章:

c# - Azure Durable Functions - HostBuilder 的等效项在哪里?

javascript - 使用支持 Javascript 的 WCF 进行错误处理?

wcf - 在控制台中托管简单的 Wcf 服务

android - 如何授予我的系统应用程序 root 权限以绑定(bind)特权端口?

sockets - 如何在fiddler中捕获套接字编程的发送和接收请求

c# - 生成后事件不适用于 msbuild.exe

c# - 如何让多个线程处理相同的 IEnumerable 结果?

c# - 从另一个项目 C# 调用类

c# - WCF是建立在套接字上的吗?

c++ - 服务器关闭后 TCP/IP 客户端重新连接