几个异步发送的相同缓冲区

时间:2011-01-12 19:46:56

标签: .net sockets buffer send

对多个socket :: send并行运行使用相同的缓冲区是否正确?我没有看到这个我的c#测试应用程序有任何问题。但我没有看到任何关于此的示例或文档。所以我正在寻找关于此的权威参考。

using System;
using System.Net;
using System.Net.Sockets;

namespace ReuseSocketBuffer
{
    class Program
    {
        static byte[] reciveBuffer = new byte[1024];
        static byte[] senderBuffer = new byte[1024];

        static void Main(string[] args)
        {
            var sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            listener.Bind(new IPEndPoint(IPAddress.Any, 0));
            listener.Listen(1);
            var ar1 = listener.BeginAccept(null, null);

            sender.Connect(new IPEndPoint(IPAddress.Loopback, (listener.LocalEndPoint as IPEndPoint).Port));

            var receiver = listener.EndAccept(ar1);

            receiver.BeginReceive(reciveBuffer, 0, reciveBuffer.Length, SocketFlags.None, ReceiveCallback, receiver);

            var ee = new SocketAsyncEventArgs[1024];

            senderBuffer[0] = 1;
            senderBuffer[1023] = 2;

            for (; ; )
            {
                for (int i = 0; i < ee.Length; i++)
                {
                    ee[i] = new SocketAsyncEventArgs();
                    ee[i].SetBuffer(senderBuffer, 0, senderBuffer.Length);
                }

                for (int i = 0; i < ee.Length; i++)
                    sender.SendAsync(ee[i]);
            }
        }

        static int count = 0;

        static void ReceiveCallback(IAsyncResult ar)
        {
            var receiver = ar.AsyncState as Socket;

            int received = receiver.EndReceive(ar);
            while (received < 1024)
                received += receiver.Receive(reciveBuffer, received, reciveBuffer.Length - received, SocketFlags.None);

            Console.Write("\r{0}", count++);

            if (reciveBuffer[0] != 1 || reciveBuffer[1023] != 2)
                throw new Exception();

            receiver.BeginReceive(reciveBuffer, 0, reciveBuffer.Length, SocketFlags.None, ReceiveCallback, receiver);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

只要不修改缓冲区中的数据,这应该没问题。