【问题标题】:How to receive UDP packages when using UdpClient class in C#在 C# 中使用 UdpClient 类时如何接收 UDP 包
【发布时间】:2015-04-12 11:17:14
【问题描述】:

我正在尝试编写一个可以与我的 Node.js 服务器通信的图形 C# 程序。

我正在使用 UdpClient 类,并且能够向服务器发送一些消息。

但是,我不知道如何从服务器接收 UDP 包。 JavaScript 和 Windows 窗体小部件是事件驱动的,但 C# 中的 UdpClient 类没有任何与数据接收相关的方便事件。

另外,我不知道将包裹接收代码放在哪里。大多数在线示例都是控制台程序,我的程序是基于 GUI 的。

我希望我的程序持续监听一个端口,当一个包进来时,程序可以捕获这个包并将其内容显示在一个 TextBox 中。

有什么建议吗?

【问题讨论】:

  • 您可以使用外部库吗? (在服务器和客户端)

标签: c# .net udpclient


【解决方案1】:

您可以使用BeginReceive 异步监听端口。它也适用于 GUI 应用程序 - 只需记住在与 UI 交互之前将数据发送到 UI 线程即可。

此示例来自 WinForms 应用程序。我在名为txtLog 的表单上放置了一个多行文本框。

private const int MyPort = 1337;
private UdpClient Client;

public Form1() {
    InitializeComponent();

    // Create the UdpClient and start listening.
    Client = new UdpClient(MyPort);
    Client.BeginReceive(DataReceived, null);
}

private void DataReceived(IAsyncResult ar) {
    IPEndPoint ip = new IPEndPoint(IPAddress.Any, MyPort);
    byte[] data;
    try {
        data = Client.EndReceive(ar, ref ip);

        if (data.Length == 0)
            return; // No more to receive
        Client.BeginReceive(DataReceived, null);
    } catch (ObjectDisposedException) {
        return; // Connection closed
    }

    // Send the data to the UI thread
    this.BeginInvoke((Action<IPEndPoint, string>)DataReceivedUI, ip, Encoding.UTF8.GetString(data));
}

private void DataReceivedUI(IPEndPoint endPoint, string data) {
    txtLog.AppendText("[" + endPoint.ToString() + "] " + data + Environment.NewLine);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    相关资源
    最近更新 更多