で放送する番組があり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
ください! ありがとう!