none
How to specify the number of bytes to send when using Socket.SendToAsync()? RRS feed

  • Question

  • I have ported my UDP based protocol implementation from using the Socket.BeginXXX methods to the Socket.XXXAsync methods as they take the SocketAsyncEventArgs class which has Buffer, Offset and Count properties so a single large buffer can be segmented and used for each operation.

    Unfortunately I have just found out setting:

    mySocketAsyncEventArgs.SendPacketsSendSize

    Is not used when sending datagrams using:

    mySocket.SendToAsync(mySocketAsyncEventArgs);

    Instead the whole segment in SocketAsyncEventArgs.Buffer from Offset for Count bytes is sent! And I cannot use Socket.SendPacketsElements because that is only for connected Sockets!

    Often I will only have a few bytes to send, but sometimes a thousand.. If the whole point of these overloads was to increase efficiency - they are not helping!

    Please tell me there is way to specify the number of bytes to send in SocketAsyncEventArgs.Buffer on each operation..

    Monday, August 5, 2013 12:24 AM

Answers

  • You can use the SetBuffer() overload where you do not have to pass a new byte[] buffer - just adjust the existing index and count to be used - then after the operation set count back to it's original value:

    mySocketAsyncEventArgs.SetBuffer(mySocketAsyncEventArgs.Offset, numOfBytesWritten);
    mySocket.SendToAsync(mySocketAsyncEventArgs);
    ...
    mySocketAsyncEventArgs.SetBuffer(mySocketAsyncEventArgs.Offset, originalBufferSize);

    • Marked as answer by markmnl Monday, August 5, 2013 11:22 AM
    Monday, August 5, 2013 11:22 AM

All replies