6

这个简单的 WCF 发现示例在单台机器上工作,但是当客户端和服务器在同一子网中的不同机器上运行且没有防火墙时,它就不起作用了。我错过了什么?

using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.ServiceModel;
using System.ServiceModel.Discovery;

namespace WCFDiscovery
{
   class Program
   {
      static void Main(string[] args)
      {
         try { if (args.Length > 0) StartClient(); else StartServer(); }
         catch (Exception ex) { Console.WriteLine(ex); }
         finally { Console.WriteLine("press enter to quit..."); Console.ReadLine(); }
      }

      private static void StartServer()
      {
         var ipAddress = Dns.GetHostAddresses(Dns.GetHostName()).First(ip => ip.AddressFamily == AddressFamily.InterNetwork);
         var address = new Uri(string.Format("net.tcp://{0}:3702", ipAddress));
         var host = new ServiceHost(typeof(Service), address);
         host.AddServiceEndpoint(typeof(IService), new NetTcpBinding(), address);
         host.Description.Behaviors.Add(new ServiceDiscoveryBehavior());
         host.AddServiceEndpoint(new UdpDiscoveryEndpoint());
         host.Open();
         Console.WriteLine("Started on {0}", address);
      }

      private static void StartClient()
      {
         var dc = new DiscoveryClient(new UdpDiscoveryEndpoint());
         Console.WriteLine("Searching for service...");
         var findResponse = dc.Find(new FindCriteria(typeof(IService)));
         var response = ChannelFactory<IService>.CreateChannel(new NetTcpBinding(), findResponse.Endpoints[0].Address).Add(1, 2);
         Console.WriteLine("Service response: {0}", response);
      }
   }

   [ServiceContract] interface IService { [OperationContract] int Add(int x, int y); }

   class Service : IService { public int Add(int x, int y) { return x + y; } }
}
4

2 回答 2

2

我已经在 2 台不同的机器(笔记本(Win7)和塔式 PC(Win8)、.NET FW 4.5、相同的 WiFi 网络)上运行了您的代码,并收到以下异常:

A remote side security requirement was not fulfilled during authentication. Try increasing the ProtectionLevel and/or ImpersonationLevel.

这是由于未指定服务安全性,找到了端点。因此,其他答案中的人是对的-这是一个无法通过更正代码来解决的网络问题。我要补充一点,问题的另一个可能来源可能是网络交换机不允许 UDP 广播。

于 2013-01-03T18:12:46.117 回答
1

需要明确的是,Windows防火墙是否也关闭了?

还要确保将服务器绑定到其他计算机用来与之通信的地址。

本地主机或 127.0.0.1 可能不会连接到其外部(到主机)可寻址 IP,这是多播发现数据包将到达的地址。

关于关闭 Windows 防火墙的 MSDN 说明

于 2012-12-27T18:37:02.983 回答