C#广播是UDP消息,侦听多个答复 [英] C# Broadcast is UDP message, listen for multiple replies

查看:203
本文介绍了C#广播是UDP消息,侦听多个答复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我在Java中有此功能(工作正常),它在其中将DatagramPacket广播发送到组地址224.168.101.200。然后有一个工作线程,该线程继续侦听来自同一套接字的传入DatagramPackets。

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.

推荐答案

以您为例,您可以比较出了什么问题。我创建了一个带有2个文本框和一个按钮的Windows窗体应用程序。

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));
    }
}

这篇关于C#广播是UDP消息,侦听多个答复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆