C#Broadcast是UDP消息,收听多个回复

时间:2017-03-29 20:39:44

标签: c# udp broadcast udpclient

我正在尝试编写一些执行UDP广播的代码,然后侦听来自远程服务器的回复,说明它们存在。它用于识别在子网上运行服务器应用程序的机器,因此基本上会发出“谁在那里?”并听取所有回复。

我在Java中使用它(完美地工作),它将DatagramPacket广播发送到组地址224.168.101.200。然后有一个工作线程,它一直在监听同一个套接字上的传入DatagramPackets。

Thisthis不是答案,因为他们说如何在不同的机器上发送和收听。

1 个答案:

答案 0 :(得分:1)

刚刚为你做了一个实例,你可以比较出错的地方。我创建了一个带有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));
    }
}