2009-11-01 92 views
2

我試圖發送一個廣播,然後讓服務器回覆成廣播:發送答覆與插座

public static void SendBroadcast() 
    { 
     byte[] buffer = new byte[1024]; 
     var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 
     socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); 

     socket.Connect(new IPEndPoint(IPAddress.Broadcast, 16789)); 
     socket.Send(System.Text.UTF8Encoding.UTF8.GetBytes("Anyone out there?")); 

     var ep = socket.LocalEndPoint; 

     socket.Close(); 

     socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 

     socket.Bind(ep); 
     socket.Receive(buffer); 
     var data = UTF8Encoding.UTF8.GetString(buffer); 
     Console.WriteLine("Got reply: " + data); 

     socket.Close(); 
    } 

    public static void ReceiveBroadcast() 
    { 
     byte[] buffer = new byte[1024]; 

     var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 
     var iep = new IPEndPoint(IPAddress.Any, 16789); 
     socket.Bind(iep); 

     var ep = iep as EndPoint; 
     socket.ReceiveFrom(buffer, ref ep); 
     var data = Encoding.UTF8.GetString(buffer); 

     Console.WriteLine("Received broadcast: " + data + " from: " + ep.ToString()); 

     buffer = UTF8Encoding.UTF8.GetBytes("Yeah me!"); 
     socket.SendTo(buffer, ep); 

     socket.Close(); 
    } 

廣播到達罰款,但答覆沒有。沒有例外被拋出。誰能幫我?我是否必須爲回覆或其他內容打開新的連接?

編輯:改變了我的代碼了一下,現在它的工作!感謝您的回覆!

回答

4

它看起來不像你的SendBroadcast()套接字綁定到一個端口,所以他不會收到任何東西。事實上,你的ReceiveBroadcast()套接字將回復發送回他自己的端口,所以他將收到他自己的回覆。

ReceiveBroadcast: binds to port 16789 
SendBroadcast: sends to port 16789 
ReceiveBroadcast: receives datagram on port 16789 
ReceiveBroadcast: sends reply to 16789 
ReceiveBroadcast: **would receive own datagram if SendTo follwed by Receive** 

你需要(一)有SendBroadcast()綁定到不同端口和改變ReceiveBroadcast()發送到端口(而不是他自己的端點ep),或(b)有兩個功能使用相同的Socket對象所以他們可以接收數據包在端口16789.

+0

你說得對,謝謝! – eWolf 2009-11-01 19:04:14