所以我一直在使用c#中的聊天应用程序作为Windows窗体应用程序,当这个代码接收数据时必须执行程序冻结.
任何人都请帮助我,发现这是错误的.作为控制台应用程序,它工作.
UdpClient udpClient = new UdpClient(Convert.ToInt32(textPort.Text));
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
textMsg.Text = returnData.ToString();
Run Code Online (Sandbox Code Playgroud)
您的程序被冻结,因为UdpClient类的Receive(...)方法是阻塞的.
也就是说,它将在执行点停止,并且不允许它所处的线程/进程继续,直到它收到单个 UDP数据包.这包括UI,除非您将其放在单独的线程中或我们使用异步通信模型.
如果要异步处理通信,请查看BeginReceive(...)方法.
这里有一些示例代码(最初,我直接从Microsoft使用此代码.但是,它缺少UdpState的定义.经过一些牙齿咬牙切齿,我发现你必须创建它来传递你自己的状态所以异步模型将按预期工作.该示例已更新并在VS2008,.Net 3.5)中编译:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleApplication1
{
class UdpState
{
public IPEndPoint e = null;
public UdpClient u = null;
}
class Program
{
public static bool messageReceived = false;
public static void ReceiveCallback(IAsyncResult ar)
{
UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;
Byte[] receiveBytes = u.EndReceive(ar, ref e);
string receiveString = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("Received: {0}", receiveString);
messageReceived = true;
}
public static void ReceiveMessages(int listenPort)
{
// Receive a message and write it to the console.
IPEndPoint e = new IPEndPoint(IPAddress.Any, listenPort);
UdpClient u = new UdpClient(e);
UdpState s = new UdpState();
s.e = e;
s.u = u;
Console.WriteLine("listening for messages");
u.BeginReceive(new AsyncCallback(ReceiveCallback), s);
// Do some work while we wait for a message. For this example,
// we'll just sleep
while (!messageReceived)
{
Thread.Sleep(100);
}
}
static void Main(string[] args)
{
ReceiveMessages(10000);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个有帮助吗?