我一直在寻找通过UdpClient
中C#
课程接收和处理消息的最佳解决方案。有没有人对此有任何解决方案?
答案 0 :(得分:39)
试试这段代码:
//Client uses as receive udp client
UdpClient Client = new UdpClient(Port);
try
{
Client.BeginReceive(new AsyncCallback(recv), null);
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
//CallBack
private void recv(IAsyncResult res)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 8000);
byte[] received = Client.EndReceive(res, ref RemoteIpEndPoint);
//Process codes
MessageBox.Show(Encoding.UTF8.GetString(received));
Client.BeginReceive(new AsyncCallback(recv), null);
}
答案 1 :(得分:17)
对于使用TAP而不是Begin / End方法的较新方法,您可以在.Net 4.5中使用以下内容
非常简单!
private static void UDPListener()
{
Task.Run(async () =>
{
using (var udpClient = new UdpClient(11000))
{
string loggingEvent = "";
while (true)
{
//IPEndPoint object will allow us to read datagrams sent from any source.
var receivedResults = await udpClient.ReceiveAsync();
loggingEvent += Encoding.ASCII.GetString(receivedResults.Buffer);
}
}
});
}
与上面的asynchronous
方法相符,这也可以用synchronous
方法以非常类似的方式实现:
private static void UDPListener()
{
Task.Run(() =>
{
using (var udpClient = new UdpClient(11000))
{
string loggingEvent = "";
while (true)
{
//IPEndPoint object will allow us to read datagrams sent from any source.
var remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
var receivedResults = udpClient.Receive(ref remoteEndPoint);
loggingEvent += Encoding.ASCII.GetString(receivedResults);
}
}
});
}
答案 2 :(得分:0)
我可以推荐两个关于此解决方案的链接,这些链接对我有帮助。
第一个是非常简单的解决方案,但要小心修改,因为只有当一些UDP数据包作为第一个发送到“远程”设备时,连续接收才会起作用。 对于连续监听,添加代码行“udp.BeginReceive(new AsyncCallback(UDP_IncomingData),udp_ep);”在每次读取数据后,都可以重新接收UDP数据包。
第二个是使用多播IP地址的好方法(239.255.255.255 - 240.0.0.0)