9

我想做这个

for (int i = 0; i < 100; i++ )
{
    Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
}

UdpClient.Receive我必须使用 ,而不是使用UdpClient.BeginReceive。问题是,我该怎么做?使用BeginReceive的示例并不多,而且 MSDN 示例根本没有帮助。我应该使用BeginReceive,还是只在单独的线程下创建它?

我一直得到ObjectDisposedException例外。我只收到发送的第一个数据。下一个数据将抛出异常。

public class UdpReceiver
{
    private UdpClient _client;
    public System.Net.Sockets.UdpClient Client
    {
        get { return _client; }
        set { _client = value; }
    }
    private IPEndPoint _endPoint;
    public System.Net.IPEndPoint EndPoint
    {
        get { return _endPoint; }
        set { _endPoint = value; }
    }
    private int _packetCount;
    public int PacketCount
    {
        get { return _packetCount; }
        set { _packetCount = value; }
    }
    private string _buffers;
    public string Buffers
    {
        get { return _buffers; }
        set { _buffers = value; }
    }
    private Int32 _counter;
    public System.Int32 Counter
    {
        get { return _counter; }
        set { _counter = value; }
    }
    private Int32 _maxTransmission;
    public System.Int32 MaxTransmission
    {
        get { return _maxTransmission; }
        set { _maxTransmission = value; }
    }

    public UdpReceiver(UdpClient udpClient, IPEndPoint ipEndPoint, string buffers, Int32 counter, Int32 maxTransmission)
    {
        _client = udpClient;
        _endPoint = ipEndPoint;
        _buffers = buffers;
        _counter = counter;
        _maxTransmission = maxTransmission;
    }
    public void StartReceive()
    {
        _packetCount = 0;
        _client.BeginReceive(new AsyncCallback(Callback), null);
    }

    private void Callback(IAsyncResult result)
    {
        try
        {
            byte[] buffer = _client.EndReceive(result, ref _endPoint);
            // Process buffer
            MainWindow.Log(Encoding.ASCII.GetString(buffer));
            _packetCount += 1;
            if (_packetCount < _maxTransmission)
            {
                _client.BeginReceive(new AsyncCallback(Callback), null);
            }
        }
        catch (ObjectDisposedException ex) 
        {
            MainWindow.Log(ex.ToString());
        }
        catch (SocketException ex) 
        { 
            MainWindow.Log(ex.ToString()); 
        }
        catch (System.Exception ex)
        {
            MainWindow.Log(ex.ToString()); 
        }
    }
}

是什么赋予了?

顺便说一下,总体思路是:

  1. 创建 tcpclient 管理器。
  2. 使用 udpclient 开始发送/接收数据。
  3. 当所有数据都发送完毕后,tcpclient 管理器将向接收者发出所有数据已发送的信号,并且应该关闭 udpclient 连接。
4

5 回答 5

7

似乎UdpClient.BeginReceive()UdpClient.EndReceive()没有很好地实施/理解。当然,与 TcpListener 的实现方式相比,使用起来要困难得多。

您可以做几件事来UdpClient.Receive()更好地使用这项工作。首先,在底层套接字客户端上设置超时将使控制失败(异常),允许控制流继续或循环。其次,通过在新线程上创建 UDP 侦听器(我没有展示它的创建),您可以避免UdpClient.Receive()函数的半阻塞效应,并且如果操作正确,您可以在以后有效地中止该线程。

下面的代码分为三个部分。第一部分和最后一部分应分别位于入口和出口点的主循环中。第二部分应该在您创建的新线程中。

一个简单的例子:

// Define this globally, on your main thread
UdpClient listener = null;
// ...


// ...
// Create a new thread and run this code:

IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 9999);
byte[] data = new byte[0];
string message = "";

listener.Client.SendTimeout = 5000;
listener.Client.ReceiveTimeout = 5000;

listener = new UdpClient(endPoint);
while(true)
{
    try
    {
        data = listener.Receive(ref endPoint);
        message = Encoding.ASCII.GetString(data);
    }
    catch(System.Net.Socket.SocketException ex)
    {
        if (ex.ErrorCode != 10060)
        {
            // Handle the error. 10060 is a timeout error, which is expected.
        }
    }

    // Do something else here.
    // ...
    //
    // If your process is eating CPU, you may want to sleep briefly
    // System.Threading.Thread.Sleep(10);
}
// ...


// ...
// Back on your main thread, when it's exiting, run this code
// in order to completely kill off the UDP thread you created above:
listener.Close();
thread.Close();
thread.Abort();
thread.Join(5000);
thread = null;

除此之外,您还可以检查UdpClient.Available > 0以确定是否有任何 UDP 请求在执行之前排队UdpClient.Receive()- 这完全消除了阻塞方面。我建议您谨慎尝试,因为此行为未出现在 Microsoft 文档中,但似乎确实有效。

笔记:

您在研究此问题时可能发现的MSDN 示例代码需要一个额外的用户定义类- UdpState。这不是 .NET 库类。这似乎让很多人在研究这个问题时感到困惑。

不必严格设置超时以使您的应用程序完全退出,但它们将允许您在该循环中执行其他操作,而不是永远阻塞。

listener.Close()命令很重要,因为它强制 UdpClient 抛出异常并退出循环,从而允许处理 Thread.Abort()。如果没有这个,您可能无法正确终止侦听器线程,直到它超时或接收到 UDP 数据包导致代码继续通过 UdpClient.Receive() 块。


只是为了添加这个无价的答案,这里有一个工作和测试的代码片段。(这里是 Unity3D 上下文,但当然适用于任何 c#。)

// minmal flawless UDP listener per PretorianNZ

using System.Collections;
using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;

void Start()
   {
   listenThread = new Thread (new ThreadStart (SimplestReceiver));
   listenThread.Start();
   }

private Thread listenThread;
private UdpClient listenClient;
private void SimplestReceiver()
   {
   Debug.Log(",,,,,,,,,,,, Overall listener thread started.");

   IPEndPoint listenEndPoint = new IPEndPoint(IPAddress.Any, 1260);
   listenClient = new UdpClient(listenEndPoint);
   Debug.Log(",,,,,,,,,,,, listen client started.");

   while(true)
      {
      Debug.Log(",,,,, listen client listening");

      try
         {
         Byte[] data = listenClient.Receive(ref listenEndPoint);
         string message = Encoding.ASCII.GetString(data);
         Debug.Log("Listener heard: " +message);
         }
      catch( SocketException ex)
         {
         if (ex.ErrorCode != 10060)
            Debug.Log("a more serious error " +ex.ErrorCode);
         else
            Debug.Log("expected timeout error");
         }

      Thread.Sleep(10); // tune for your situation, can usually be omitted
      }
   }

void OnDestroy() { CleanUp(); }
void OnDisable() { CleanUp(); }
// be certain to catch ALL possibilities of exit in your environment,
// or else the thread will typically live on beyond the app quitting.

void CleanUp()
   {
   Debug.Log ("Cleanup for listener...");

   // note, consider carefully that it may not be running
   listenClient.Close();
   Debug.Log(",,,,, listen client correctly stopped");

   listenThread.Abort();
   listenThread.Join(5000);
   listenThread = null;
   Debug.Log(",,,,, listener thread correctly stopped");
   }
于 2014-02-19T23:23:58.830 回答
4

我认为你不应该在循环中使用它,而是在调用 BeginReceive 回调时再次调用 BeginReceive,如果你想将数字限制为 100,则保留一个公共变量用于计数。

于 2010-11-07T14:51:42.973 回答
3

先看看MSDN。他们提供了很好的例子。 http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.beginreceive.aspx

于 2010-11-07T14:52:32.210 回答
2

我会在后台线程上进行网络通信,这样它就不会阻塞应用程序中的任何其他内容。

BeginReceive 的问题是您必须在某个时候调用 EndReceive(否则您有等待句柄) - 并且调用 EndReceive 将阻塞,直到接收完成。这就是为什么将通信放在另一个线程上更容易的原因。

于 2010-11-07T14:54:37.937 回答
0

您必须在另一个线程(或任务)上进行网络操作、文件操作和依赖于其他事情而不是您自己的程序的事情,因为它们可能会冻结您的程序。原因是您的代码按顺序执行。您已经在一个不好的循环中使用它。每当BeginRecieve调用回调时,您都应该再次调用它。看看下面的代码

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()
{
  // 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);
  }
}
于 2017-10-20T20:39:32.763 回答