2014-02-13 208 views
0

我在播放和接收UDP消息。 我有一臺客戶端和一臺服務器,可以在我的機器上正常工作,但不能跨機器連接。使用UdpClient廣播和接收消息

我的服務器發送消息,我的客戶端收到它們。 我在兩臺機器上都轉過了防火牆,這不成問題。

服務器看起來像:

var udpclient = new UdpClient(); 

IPAddress multicastAddress = IPAddress.Parse("239.0.0.222"); 
udpclient.JoinMulticastGroup(multicastAddress); 
var endPoint = new IPEndPoint(multicastAddress, 2222); 

while(true) 
{ 
    Byte[] buffer = Encoding.Unicode.GetBytes(Dns.GetHostName()); 
    udpclient.Send(buffer, buffer.Length, endPoint); 

    Console.WriteLine("Broadcasting server hostname: {0}", Dns.GetHostName()); 
    Thread.Sleep(3000); 
} 

而客戶端的樣子:

var client = new UdpClient { ExclusiveAddressUse = false }; 

var ipEndPoint = new IPEndPoint(IPAddress.Any, 2222); 

client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); 
client.ExclusiveAddressUse = false; 

client.Client.Bind(ipEndPoint); 

IPAddress multicastaddress = IPAddress.Parse("239.0.0.222"); 
client.JoinMulticastGroup(multicastaddress); 

Byte[] data = client.Receive(ref ipEndPoint); 
string strData = Encoding.Unicode.GetString(data); 
Console.WriteLine("Received hostname {0} from the server", strData); 

Console.WriteLine("I'm done. Press any key to close me."); 
Console.ReadLine(); 

我覺得這個問題是不是在代碼中,而是與網絡相關的。 有關如何檢查問題的任何想法?預先感謝您

+0

嘗試先做一個TCP連接,看看你是否可以讓他們互相交談。 UDP是無連接協議,不保證消息到達目的地。 –

+0

我的想法是在不知道對方的情況下連接服務器和客戶端。服務器通過Udp廣播它的IP,客戶端選擇它並建立與服務器的tcp連接。但我可以嘗試TCP,只是爲了測試。謝謝回覆。 – Dante

回答

-2

嘗試將它們連接到相同的網絡,如WiFi網絡。注意:每次連接到不同的網絡時,IP地址會發生變化。