The reason you get the exception is because under the hood of SocketAsyncEventArgs , only the buffers that are in the list when setting the BufferList property are BufferList . Basically you are trying to send an empty buffer with code:
e.BufferList = new List<ArraySegment<byte>>(); e.BufferList.Add(new ArraySegment<byte>(lTxBytes)); e.BufferList.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lTx.Identity))); e.BufferList.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lResponse)));
Instead, try doing:
var list = new List<ArraySegment<byte>>(); list.Add(new ArraySegment<byte>(lTxBytes)); list.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lTx.Identity))); list.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lResponse))); e.BufferList = list;
This behavior is not documented at all and can only be understood by looking at the set BufferList code in detail. Behind the scenes, SocketAsyncEventArgs has a WSABuffer array WSABuffer (for interacting with native code), where it copies and provides links to byte arrays when setting BufferList . Since this WSABuffer[] sent in native code, this explains why your code throws an exception.
Jj15k
source share