C# Socket.BeginReceive/EndReceive

The order in time should be:

  1. BeginReceive for message length
  2. EndReceive for the completion of #1
  3. BeginReceive for the message body
  4. EndReceive for the completion of #3

E.g. not using callbacks you could have:

var sync = socket.BeginReceive(....);
sync.AsyncWaitHandle.WaitOne();
var res = socket.EndReceive(sync);
sync = socket.BeginReceive(....);
sync.AsyncWaitHandle.WaitOne();
var res2 = socket.EndReceive(sync);

But then, you would be better just using Receive!

I think you might find it easier to use separate handlers for the two different receives:

... Start(....) {
    sync = socket.BeginReceive(.... MessageLengthReceived, null);
}

private void MessageLengthReceived(IAsyncResult sync) {
  var len = socket.EndReceive(sync);
  // ... set up buffer etc. for message receive

 sync = socket.BeginReceive(... MessageReceived, null);
}

private void MessageReceived(IAsyncResult sync) {
  var len = socket.EndReceive(sync);
  // ... process message
}

Ultimately putting all the associated in a state object and passing that around (in the completion delegate access via IAsyncResult.AsyncState) from BeginReceive can make things easier, but does take a shift from the linear thinking of imperative code and fulling embracing a event driven approach.


2012 Addendum:

.NET 4.5 Version

With the async support in C#5 there is a new option. This uses the compiler to generate the manual continuations (the separate callback methods) and closures (state) from inline code. However there are two things to work around:

  1. While System.Net.Sockets.Socket has various …Async methods these are for the event based asynchronous pattern, not the Task based pattern that C#5’s await uses. Solution: use TaskFactory.FromAsync to get a single Task<T> from a Begin… End… pair.

  2. TaskFactory.FromAsync only supports passing up to three additional arguments (in addition to the callback and state) to Begin…. Solution: a lambda taking zero additional arguments has the right signature, and C# will give us the right closure to pass the arguments in.

Hence (and more fully realised with Message being another type that handles the conversion from an initial send of the length encoded in some fixed number of bytes then the content bytes into a length for the content’s buffer):

private async Task<Message> ReceiveAMessage() {
  var prefix = new byte[Message.PrefixLength];

  var revcLen = await Task.Factory.FromAsync(
                         (cb, s) => clientSocket.BeginReceive(prefix, 0, prefix.Length, SocketFlags.None, cb, s),
                         ias => clientSocket.EndReceive(ias),
                         null);
  if (revcLen != prefix.Length) { throw new ApplicationException("Failed to receive prefix"); }
  
  int contentLength = Message.GetLengthFromPrefix(prefix);
  var content = new byte[contentLength];
  
  revcLen = await Task.Factory.FromAsync(
                         (cb, s) => clientSocket.BeginReceive(content, 0, content.Length, SocketFlags.None, cb, s),
                         ias => clientSocket.EndReceive(ias),
                         null);
  if (revcLen != content.Length) { throw new ApplicationException("Failed to receive content"); }
  
  return new Message(content);
}

Leave a Comment