0
對於多個套接字::發送並行運行使用相同的緩衝區是否正確?我沒有看到這個我的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);
}
}
}