.NET中最快的UDP侦听器套接字

时间:2015-09-11 12:36:35

标签: c# .net performance sockets udp

大家好,我想知道什么是最快的UDP数据包读取机制。

我在考虑使用套接字异步接收,这应该是接收数据的最快方式。然后在不同的线程中进行处理循环。

这真的是最快的方法吗?

static Socket udpListener;
static byte[] buffer = new byte[5000];
static ConcurrentQueue<byte[]> recievedPackets = new ConcurrentQueue<byte[]>();

static void Main(string[] args)
{
    udpListener = new Socket(SocketType.Dgram, ProtocolType.Udp);
    udpListener.Bind(new IPEndPoint(IPAddress.Any, 50000));

    StartRecievingChain();

    // Processing loop
    Task.Factory.StartNew(() =>
    {
        int counter = 0;
        while (true)
        {
            if (recievedPackets.Count == 0)
                Thread.Sleep(50);

            byte[] packet;

            if (recievedPackets.TryDequeue(out packet))
            {
                counter++;
                Console.WriteLine("Recieved {0} bytes", packet.Length);
            }
        }
    });

    Console.ReadKey();
}

static void StartRecievingChain()
{
    SocketAsyncEventArgs recieveArgs = new SocketAsyncEventArgs();
    recieveArgs.SetBuffer(buffer, 0, buffer.Length);
    recieveArgs.Completed += ProcessRecievedPacket;

    if (!udpListener.ReceiveAsync(recieveArgs))
        ProcessRecievedPacket(null, recieveArgs);
}

static void ProcessRecievedPacket(object sender, SocketAsyncEventArgs e)
{
    try
    {
        if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
        {
            StartRecievingChain();

            byte[] data = new byte[e.BytesTransferred];
            Array.Copy(e.Buffer, data, e.BytesTransferred);
            recievedPackets.Enqueue(data);
        }
    }
    finally
    {
        e.Completed -= ProcessRecievedPacket;
        e.Dispose();
    }
}

0 个答案:

没有答案