Sending Page-Mode Messages Asynchronously

The asynchronous call to send a page-mode message uses the BeginSendMessageEndSendMessage pattern adopted in the .NET Framework, and recommended in this documentation. The pattern requires an application to supply a callback method that is invoked before the asynchronous operation finishes. This sample calls the BeginSendMessage(MessageType, RealTimeAddress, ContentType, [], AsyncCallback, Object) overloaded method. The EndSendMessage(IAsyncResult) method is called in the callback method, CompleteSendMessage.

RealTimeEndpoint endpoint = ...; // Assumed to be created elsewhere
RealTimeAddress target = new RealTimeAddress("sip:bob@contoso.com");
string msg = "Greetings!";
ContentType contentType = new ContentType("text/plain; charset=UTF-8");
byte[] msgBody = Encoding.UTF8.GetBytes(msg);
try
{
  endpoint.BeginSendMessage(MessageType.Message,
                            target,
                            contentType,
                            msgBody,
                            CompleteSendMessage,
                            endpoint);
}

catch (RealTimeException e)
{
  // Handle exception here.
}

// Asynchronous callback function to end the BeginSendMessage operation.
void CompleteSendMessage(AsyncCallback result)
{
  RealTimeEndpoint ep = ar.AsyncState as RealTimeEndpoint;
  SipResponseData data;
  try
  {
    data = ep.EndSendMessage(ar);
  }

  catch (FailureResponseException exp)
  {
    // Handle a failure response.
    Console.WriteLine("Failure response for {0}: {1}", ep.Uri, exp.ToString());
  }

  catch (OperationTimeoutException exp)
  {
    // The operation timed out.
    Console.WriteLine("Operation timed out for {0}: {1}", ep.Uri, exp.ToString());
  }

  catch (RealTimeException exp)
  {
    // Handle exception.
    Console.WriteLine("Invite Failure for {0}: {1}", ep.Uri, exp.ToString());
  }
}