【问题标题】:C# Receiving UDP dataC#接收UDP数据
【发布时间】:2018-12-18 04:44:18
【问题描述】:

我正在尝试学习 C# 中的 UDP 套接字编程。我已经制作了一个将发送数据的 WinForm,代码如下所示。这是一个带有三个文本框和一个按钮的小表单。

using System;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace UDP_example

{
    public partial class Form1 : Form1
    {
    public Form1()
    {
        InitializeComponent();
    }

    private void btnSend_Click(object sender, EventArgs e)
    {
        // make sure all text boxes contain data, or do nothing.
        if (string.IsNullOrEmpty(txtIP.Text)) return;
        if (string.IsNullOrEmpty(txtPort.Text)) return;
        if (string.IsNullOrEmpty(txtMessage.Text)) return;

        // convert the text into byte array
        byte[] message = Encoding.ASCII.GetBytes(txtMessage.Text);
        string ipAddress = txtIP.Text;
        int sendPort = Convert.ToInt32(txtPort.Text);

        // send the data
        try
        {
            using (var client = new UdpClient())
            {
                IPEndPoint server = new IPEndPoint(IPAddress.Parse(ipAddress), sendPort);
                client.Connect(server);
                client.Send(message, message.Length);
            }
        }
        // display error if one occurs
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
        }

        // clean up
        txtMessage.Clear();
        txtMessage.Focus();
    }
}

这部分似乎工作正常。我需要的是在连接另一端的文本框或消息框中显示接收到的数据。

有人可以告诉我怎么做吗?我不知道如何基本上让套接字以异步方式侦听并在接收端显示传入数据。它只是一个带有文本框的表单或显示传入数据的单个消息框。

编辑: 这是接收代码,但我希望它从任何 IP 地址接收,而不仅仅是本地。 (找到并修改了这段代码sn-p。)

using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace UDP_Server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(ConnectUDP));
        }

        private void ConnectUDP(object state)
        {
            UdpClient subscriber = new UdpClient(4345);
            IPAddress addr = IPAddress.Parse("127.0.0.1");
            subscriber.JoinMulticastGroup(addr);
            IPEndPoint ep = null;

            byte[] pdata = subscriber.Receive(ref ep);
            string rdata = Encoding.ASCII.GetString(pdata);
            txtReceived.Text += rdata;
        }
    }
}

我今天阅读了很多样例,并在 YouTube 上观看了一些视频,但我相当坚持我认为非常简单的内容。我唯一的要求是将接收到的来自 UDP 端口的数据放入文本框中。感谢您的帮助。

【问题讨论】:

  • 您好。 UdpClient 类的文档有一个例子:docs.microsoft.com/en-us/dotnet/api/…
  • JuanR - 谢谢。我不明白收到数据时如何调用此代码。我想这是我的问题。使用 TCP,当接收到数据时,会触发并处理事件。当使用 WinForm 接收数据时,我看不到如何引发事件。
  • 史蒂夫-谢谢。如上所述,当代码用于 Windows 窗体应用程序时,我看不到在哪里“监听”和响应传入数据。再次感谢。

标签: c# winforms udp


【解决方案1】:

正如@JuanR 所述,您的服务器端需要这样的东西

// This constructor arbitrarily assigns the local port number.
UdpClient udpClient = new UdpClient(yourUDPPort);

//IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); 
string returnData = Encoding.ASCII.GetString(receiveBytes);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-01
    • 2020-07-03
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 2017-09-27
    • 2010-12-09
    相关资源
    最近更新 更多