我正在尝试编写一些执行 UDP 广播的代码,然后侦听来自远程服务器的答复,说明它们存在。它用于识别子网上运行服务器应用程序的计算机,因此基本上会发出“谁在那儿?”并听取所有答复。
我在 Java 中有这个(工作完美),它将 DatagramPacket 广播发送到组地址 224.168.101.200。然后有一个工作线程不断侦听同一套接字上传入的 DatagramPackets。
This https://stackoverflow.com/questions/10832770/sending-udp-broadcast-receiving-multiple-messages and this https://stackoverflow.com/questions/12864999/sending-and-receiving-udp-packets不是答案,因为他们说如何在不同的机器上发送和收听。
刚刚给你做了一个工作示例,你可以比较一下出了什么问题。我创建了一个带有 2 个文本框和一个按钮的 Windows 窗体应用程序。
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));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)