C# 在C中使用UdpClient类时如何接收UDP包#
我正在尝试编写一个图形C#程序,可以与Node.js服务器进行通信 我正在使用UdpClient类,并且能够向服务器发送一些消息 但是,我不知道如何从服务器接收UDP包。 JavaScript和Windows窗体小部件是事件驱动的,但C#中的UdpClient类没有任何与数据接收相关的方便事件 另外,我不知道在哪里放置包裹接收代码。大多数在线示例都是控制台程序,我的程序是基于GUI的 我希望我的程序在一个端口持续监听,当一个包进入时,程序可以捕获该包并在文本框中显示其内容C# 在C中使用UdpClient类时如何接收UDP包#,c#,.net,udpclient,C#,.net,Udpclient,我正在尝试编写一个图形C#程序,可以与Node.js服务器进行通信 我正在使用UdpClient类,并且能够向服务器发送一些消息 但是,我不知道如何从服务器接收UDP包。 JavaScript和Windows窗体小部件是事件驱动的,但C#中的UdpClient类没有任何与数据接收相关的方便事件 另外,我不知道在哪里放置包裹接收代码。大多数在线示例都是控制台程序,我的程序是基于GUI的 我希望我的程序在一个端口持续监听,当一个包进入时,程序可以捕获该包并在文本框中显示其内容 有什么建议吗?您可以使
有什么建议吗?您可以使用
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);
}
private const int MyPort=1337;
私有UDP客户机;
公共表格1(){
初始化组件();
//创建UdpClient并开始侦听。
客户端=新的UdpClient(MyPort);
Client.BeginReceive(DataReceived,null);
}
接收到私有无效数据(IAsyncResult ar){
IPEndPoint ip=新IPEndPoint(IPAddress.Any,MyPort);
字节[]数据;
试一试{
数据=Client.EndReceive(ar,参考ip);
如果(data.Length==0)
return;//不再接收
Client.BeginReceive(DataReceived,null);
}捕获(ObjectDisposedException){
return;//连接已关闭
}
//将数据发送到UI线程
this.BeginInvoke((操作)DataReceivedUI,ip,Encoding.UTF8.GetString(数据));
}
私有void DataReceivedUI(IPEndPoint端点,字符串数据){
txtLog.AppendText(“[”+endPoint.ToString()+“]”+data+Environment.NewLine);
}
是否允许您使用外部库?(在服务器和客户端中)