2012-12-27 21 views
6

這個簡單的WCF發現示例工作在一臺機器上,但工作時,客戶端和服務器在不同計算機上沒有防火牆運行在同一子網內,它不起作用。我錯過了什麼?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; } } 
} 
+0

_「時,客戶端和服務器在不同的機器上運行」 _ - 你使用不同的地址呢?另外:_「不起作用」_不是一個例外。顯示確切的消息。 – CodeCaster

+0

服務器在端口8000監聽到「不工作」的意思是「dc.Find(......)」返回零端點所以這段代碼「終點[0]」將引發ArgumentOutOfRangeException – Robin

+1

這有什麼區別,如果您將「localhost」更改爲您的客戶端將連接到的服務器的IP地址? – sclarson

回答

2

我已經運行在兩臺不同的機器代碼(筆記本電腦(Win7的)和塔式PC(Win8的),.NET 4.5 FW,同一WiFi網絡),並收到以下異常:

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

這一個是由於服務安全性被低估,終端被找到。所以,其他人的答案是正確的 - 這是一個網絡問題,無法通過糾正代碼來解決。 我想補充說,另一個可能的問題來源可能是網絡交換機不允許UDP廣播。

+0

原來網絡交換機不允許UDP廣播。謝謝您的幫助。 – Robin

1

要說清楚的是,windows防火牆是否也關閉了?

另外,還要確保你在你的服務器綁定到其他計算機使用與它通信的地址。

本地主機或127.0.0.1可能不會回升到其外部(到主機)尋址IP的連接這就是多播發現數據包會到達上。

MSDN instructions on turning the windows firewall off

+0

是的,我手動關閉控制面板中兩臺機器上的防火牆,它不起作用。這兩款機器都是使用.NET 4.0的Windows 7 – Robin

+0

我更新了上面的代碼而不是硬代碼「localhost」,但結果是一樣的。 – Robin

+0

您的路由器是否有可能阻塞此端口的單獨防火牆?如果是這種情況,可能想查看端口轉發。 – vesuvious

相關問題