问题
I am trying to write some code that does a UDP broadcast, and then listens to replies from remote servers saying they exist. It's used to identify machines running a server app on the subnet so basically sends out a "who's there?" and listens for all the replies.
I have this in Java (works perfectly) where it sends a DatagramPacket broadcasting to a group address of 224.168.101.200. and then has a worker thread that keeps listening for incoming DatagramPackets coming in on the same socket.
This and this are not the answer as they say how to have the send and listen on different machines.
回答1:
Just made a working example for you, you could compare what went wrong. I created a windows forms applications with 2 textboxes and a button.
public partial class Form1 : Form
{
private int _port = 28000;
private string _multicastGroupAddress = "239.1.1.1";
private UdpClient _sender;
private UdpClient _receiver;
private Thread _receiveThread;
private void UpdateMessages(IPEndPoint sender, string message)
{
textBox1.Text += $"{sender} | {message}\r\n";
}
public Form1()
{
InitializeComponent();
_receiver = new UdpClient();
_receiver.JoinMulticastGroup(IPAddress.Parse(_multicastGroupAddress));
_receiver.Client.Bind(new IPEndPoint(IPAddress.Any, _port));
_receiveThread = new Thread(() =>
{
while (true)
{
IPEndPoint sentBy = new IPEndPoint(IPAddress.Any, _port);
var dataGram = _receiver.Receive(ref sentBy);
textBox1.BeginInvoke(
new Action<IPEndPoint, string>(UpdateMessages),
sentBy,
Encoding.UTF8.GetString(dataGram));
}
});
_receiveThread.IsBackground = true;
_receiveThread.Start();
_sender = new UdpClient();
_sender.JoinMulticastGroup(IPAddress.Parse(_multicastGroupAddress));
}
private void button1_Click(object sender, EventArgs e)
{
var data = Encoding.UTF8.GetBytes(textBox2.Text);
_sender.Send(data, data.Length, new IPEndPoint(IPAddress.Broadcast, _port));
}
}
来源:https://stackoverflow.com/questions/43103714/c-sharp-broadcast-is-udp-message-listen-for-multiple-replies