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();
}
廣播到達罰款,但答覆沒有。沒有例外被拋出。誰能幫我?我是否必須爲回覆或其他內容打開新的連接?
編輯:改變了我的代碼了一下,現在它的工作!感謝您的回覆!
你說得對,謝謝! – eWolf 2009-11-01 19:04:14