将BufferList与SocketAsyncEventArgs一起使用而不是获取SocketError InvalidArgument的方法如下:
public class BufferList : IList<ArraySegment<byte>>
{
private readonly List<ArraySegment<byte>> _bufferList = new List<ArraySegment<byte>>();
public ArraySegment<byte> this[int index] { get => ((IList<ArraySegment<byte>>)_bufferList)[index]; set => ((IList<ArraySegment<byte>>)_bufferList)[index] = value; }
public int Count => ((IList<ArraySegment<byte>>)_bufferList).Count;
public bool IsReadOnly => ((IList<ArraySegment<byte>>)_bufferList).IsReadOnly;
public void Add(ArraySegment<byte> item)
{
((IList<ArraySegment<byte>>)_bufferList).Add(item);
}
public void Clear()
{
((IList<ArraySegment<byte>>)_bufferList).Clear();
}
public bool Contains(ArraySegment<byte> item)
{
return ((IList<ArraySegment<byte>>)_bufferList).Contains(item);
}
public void CopyTo(ArraySegment<byte>[] array, int arrayIndex)
{
((IList<ArraySegment<byte>>)_bufferList).CopyTo(array, arrayIndex);
}
public IEnumerator<ArraySegment<byte>> GetEnumerator()
{
return ((IList<ArraySegment<byte>>)_bufferList).GetEnumerator();
}
public int IndexOf(ArraySegment<byte> item)
{
return ((IList<ArraySegment<byte>>)_bufferList).IndexOf(item);
}
public void Insert(int index, ArraySegment<byte> item)
{
((IList<ArraySegment<byte>>)_bufferList).Insert(index, item);
}
public bool Remove(ArraySegment<byte> item)
{
return ((IList<ArraySegment<byte>>)_bufferList).Remove(item);
}
public void RemoveAt(int index)
{
((IList<ArraySegment<byte>>)_bufferList).RemoveAt(index);
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IList<ArraySegment<byte>>)_bufferList).GetEnumerator();
}
}
SocketAsyncEventArgs socketAsyncEventArgs = new SocketAsyncEventArgs();
socketAsyncEventArgs.BufferList = new BufferList();
socketAsyncEventArgs.BufferList.Add(new ArraySegment<byte>(buffer1));
socketAsyncEventArgs.BufferList.Add(new ArraySegment<byte>(buffer2));
socketAsyncEventArgs.Completed += (sender, args) =>
{
if (args.SocketError == SocketError.Success)
{
// 处理发送或接收的数据
}
else
{
// 处理错误
}
};
socket.SendAsync(socketAsyncEventArgs);
// 或
socket.ReceiveAsync(socketAsyncEventArgs);
通过以上步骤,可以将BufferList与SocketAsyncEventArgs一起使用,避免出现SocketError InvalidArgument的错误。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云