4

I wanted a discoverable service that would listen on all interfaces and publish discovery announcements for each interface. I was hoping to be able to eventually just configure this in the config file using tcp://0.0.0.0:0/blah as the service endpoint. But when I run the code below, the announcements that it sends out use tcp://0.0.0.0:0/blah as the EndpointAddress which is useless to clients.

I want to receive announcements for every endpoint it derived from tcp://0.0.0.0:0/blah and I would prefer to use a config file and not a programmatic service host setup like below. Any ideas for a workaround?

    [TestFixtureSetUp]
    public void SetUp()
    {
        service1 = new MyContract();
        EndpointDiscoveryBehavior discoveryBehavior = new EndpointDiscoveryBehavior();
        ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior(discoveryUri);
        serviceDiscoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint(announcementUri));

        serviceHost1 = new ServiceHost(service1,
            new Uri[] {new Uri("net.pipe://localhost"), new Uri("net.tcp://0.0.0.0:0")});
        ServiceEndpoint localEndpoint1 = serviceHost1.AddServiceEndpoint(typeof (IContract),
            new NetNamedPipeBinding(),
            "/Pipe");
        ServiceEndpoint localEndpoint2 = serviceHost1.AddServiceEndpoint(typeof (IContract),
            new NetTcpBinding(),
            "/Tcp");
        localEndpoint2.Behaviors.Add(discoveryBehavior);
        serviceHost1.Description.Behaviors.Add(serviceDiscoveryBehavior);
        serviceHost1.AddServiceEndpoint(new UdpDiscoveryEndpoint(discoveryUri));

        serviceHost1.Open();
    }
4

2 回答 2

2

虽然我的解决方案可能不是“正确的”,但严格来说(这应该在 WCF 本身中修复,如果你问我的话),它可以工作,并且足以满足我的目的。

首先,声明一个新的端点行为,如下所示:

public class WcfDiscoveryAddressFixEndpointBehavior : IEndpointBehavior, IDispatchMessageInspector
{
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        // Attach ourselves to the MessageInspectors of reply messages
        clientRuntime.CallbackDispatchRuntime.MessageInspectors.Add(this);
    }

    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        object messageProperty;
        if (!OperationContext.Current.IncomingMessageProperties.TryGetValue(RemoteEndpointMessageProperty.Name, out messageProperty)) return null;
        var remoteEndpointProperty = messageProperty as RemoteEndpointMessageProperty;
        if (remoteEndpointProperty == null) return null;

        // Extract message body
        string messageBody;
        using (var oldMessageStream = new MemoryStream())
        {
            using (var xw = XmlWriter.Create(oldMessageStream))
            {
                request.WriteMessage(xw);
                xw.Flush();
                messageBody = Encoding.UTF8.GetString(oldMessageStream.ToArray());
            }
        }

        // Replace instances of 0.0.0.0 with actual remote endpoint address
        messageBody = messageBody.Replace("0.0.0.0", remoteEndpointProperty.Address);

        // NOTE: Do not close or dispose of this MemoryStream. It will be used by WCF down the line.
        var newMessageStream = new MemoryStream(Encoding.UTF8.GetBytes(messageBody));
        XmlDictionaryReader xdr = XmlDictionaryReader.CreateTextReader(newMessageStream, new XmlDictionaryReaderQuotas());

        // Create a new message with our modified endpoint address and
        // copy over existing properties and headers
        Message newMessage = Message.CreateMessage(xdr, int.MaxValue, request.Version);
        newMessage.Properties.CopyProperties(request.Properties);
        newMessage.Headers.CopyHeadersFrom(request.Headers);
        request = newMessage;
        return null;
    }

    public void BeforeSendReply(ref Message reply, object correlationState)
    {
    }

    public void Validate(ServiceEndpoint endpoint)
    {
    }

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
    }
}

此端点行为将原始 WCF 发现回复消息替换为副本,其中的实例0.0.0.0已替换为接收消息的地址,在RemoteEndpointMessageProperty'sAddress属性中可用。

要使用它,只需UdpDiscoveryEndpoint在创建时添加新的端点行为DiscoveryClient

var udpDiscoveryEndpoint = new UdpDiscoveryEndpoint();
udpDiscoveryEndpoint.EndpointBehaviors.Add(new WcfDiscoveryAddressFixEndpointBehavior());
_discoveryClient = new DiscoveryClient(udpDiscoveryEndpoint);

// Proceed as usual.
于 2015-02-06T06:43:06.513 回答
1

我找到了另一种无需更改消息即可工作的解决方案。

我注意到一个端点有一个address和一个listening address。这个想法是为每个 ip 地址创建一个端点,并且只共享一个监听地址(0.0.0.0 或使用机器名来获取 ipv6)。

在发现方面,将收到所有地址,有人可以尝试连接以查找其中一个可以访问。

服务器部分如下所示:

var listenUri = new Uri("net.tcp://<Environment.MachineName>:<port>/IServer";
var binding = new NetTcpBinding(SecurityMode.None);
foreach (ip address)
{ 
   var addr = new Uri("net.tcp://<ip>:<port>/IServer");
   Host.AddServiceEndpoint(typeof(IService), binding, addr, listenUri)
}
于 2018-06-10T12:39:08.743 回答