views:

189

answers:

1

As in the simplified code below, is checking that SendAsync() has finished transmitting all intended bytes in the buffer the correct thing to do? Or is that redundant? This is for a TCP connection socket. I am particularly concerned with having to issue a second sub-call to SendAsync() inside ProcessSend().

For example, if I had multiple threads transmitting data to a client using a new (pooled) SocketAsyncEventArg for each message, isn't it possible that a simultaneous send might interject itself in-between a partially transmitted message? Or is this a good reason for controlled access to the client by only allowing one SocketAsyncEventArg to be used in data sending?

private void ProcessSend(SocketAsyncEventArgs e)
{
    // Check that data was sent
    if ((e.SocketError == SocketError.Success) && (e.BytesTransferred > 0))
    {
        AsyncSendUserToken token = (AsyncSendUserToken)e.UserToken;

        // Check that all the data was sent
        int offset = e.Offset + e.BytesTransferred;
        if (offset < e.Count)
        {
            // Call send again to finish the send
            e.SetBuffer(offset, e.Count - offset);
            bool _willRaiseEvent = token.Socket.SendAsync(e);
            if (!_willRaiseEvent)
                ProcessSend(e);
        }
    }
}
A: 

I suspect you are reading the example at http://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs.aspx and see that they are checking the byte length on ProcessReceive.

This is done to in order to get all received bytes, as you have no control on how many bytes are sent from the other party each time.

When you perform a send, this is redundant as the framework handles sending all your data for you.

Mikael Svenson