我有一个节目将在255.255.255.255
. 首先,它将广播一条消息以请求 LOCATION,然后侦听回复。如果广播开始,LOCATION:
它将获得位置字符串。这是我的代码:
UDPCommunication Class
class UDPCommunication
{
public void BroadcastMessage(string message, int port)
{
BroadcastMessage(Encoding.ASCII.GetBytes(message), port);
}
private static void BroadcastMessage(byte[] message, int port)
{
using (var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp))
{
sock.EnableBroadcast = true;
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
var iep = new IPEndPoint(IPAddress.Broadcast, port);
sock.SendTo(message, iep);
}
}
public void ReceiveBroadcastMessage(Action<EndPoint, string> receivedAction, int port)
{
ReceiveBroadcastMessage((ep, data) =>
{
var stringData = Encoding.ASCII.GetString(data);
receivedAction(ep, stringData);
}, port);
}
private void ReceiveBroadcastMessage(Action<EndPoint, byte[]> receivedAction, int port)
{
using (var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
var ep = new IPEndPoint(IPAddress.Any, port) as EndPoint;
sock.Bind(ep);
while (true)
{
var buffer = new byte[1024];
var recv = sock.ReceiveFrom(buffer, ref ep);
var data = new byte[recv];
Array.Copy(buffer, 0, data, 0, recv);
receivedAction(ep, data);
Thread.Sleep(500);
Application.DoEvents();
}
}
}
}
Form1.cs
public event EventHandler BroadcastMessageArrived;
public event EventHandler LocationReceived;
string location = null;
string ReceivedMessage = null;
bool WorkDone = false;
UDPCommunication UDP = new UDPCommunication();
private void Form1_Load(object sender, EventArgs e)
{
BroadcastMessageArrived += new EventHandler(OnBroadcastMessageArrived);
LocationReceived += new EventHandler(Form1_LocationReceived);
backgroundWorker1.RunWorkerAsync();
UDP.BroadcastMessage("GATE_REQUEST_LOCATION", 15000);
while (!WorkDone) ;
LogGlobally(string.Format("Location now set to: ", Gate_Application.Properties.Settings.Default.Location));
}
void OnBroadcastMessageArrived(object sender, EventArgs e)
{
Console.WriteLine("Message received: {0}", ReceivedMessage); // Never being called
if (ReceivedMessage.StartsWith("LOCATION:"))
{
string[] LocationString = ReceivedMessage.Split(':');
location = LocationString[1];
EventHandler handler = LocationReceived;
if (handler != null)
{
handler(this, e);
}
return;
}
}
void Form1_LocationReceived(object sender, EventArgs e)
{
Gate_Application.Properties.Settings.Default.Location = location;
Gate_Application.Properties.Settings.Default.Save();
WorkDone = true;
return;
}
使用上面的代码,我尝试发送广播LOCATION:SZ
,但它从未在控制台上显示消息。我怀疑问题出在while循环上,它甚至不会中断WorkDone
,=true
请帮忙!谢谢!