Hello, dear.

I want to use asynchronous sockets for constant multi-packet transmission, I figured it out with theory, but the trouble is: I can't figure out how to transfer N bytes from the read buffer to a sheet of bytes, except by creating an intermediate array and byte-by-copy.

My code is:

public static void ReadCallback(IAsyncResult ar) { var state = (StateObject)ar.AsyncState; var handler = state.WorkSocket; var bytesRead = handler.EndReceive(ar); if (bytesRead <= 0) return; var tempBuf = new byte[bytesRead]; for (int i = 0; i < bytesRead; i++) { tempBuf[i] = state.Buffer[i]; } state.BigBuffer.AddRange(tempBuf); // Do something... handler.BeginReceive(state.Buffer, 0, BufferSize, SocketFlags.None, ReadCallback, state); } 

I would like to hear tips on how to optimize this business.

PS: List<byte> BigBuffer; BufferSize = 4096; List<byte> BigBuffer; BufferSize = 4096;

    1 answer 1

    Look in the direction of the MemoryStream in conjunction with the BinaryReader / BinaryWriter. Just do not forget that the MemoryStream works with an unmanaged resource, the output - use Dispose () or using (MemoryStream ms = new MemoryStream (...))