开发者

same buffer for several async sends

Is it correct to use same buffer for multiple socket::send running in parallel? I do not see any issue with this my c# test application. But I have not see any examples or docs for this. So I am looking for authoritative references about this.

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, re开发者_StackOverflow中文版ceived, 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);
        }
    }
}


This should be fine as long as you don't modify the data in the buffer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜