Thursday, May 17, 2012

Fielding HTTP Requests

Fielding HttpPost Requests with WCF

Uri baseAddress = new Uri("http://localhost:8/Task");
m_Host = new WebServiceHost(typeof(TaskReceiver), baseAddress);
m_Host.Open();


Console.WriteLine("The service is ready at {0}", baseAddress);
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();


if (m_Host != null)
{
if (m_Host.State == CommunicationState.Opened)
{
   m_Host.Close();
}
(m_Host as IDisposable).Dispose();
}


    [ServiceContract]
    public interface ITaskReceiver
    {
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "")]
        string EnqueueTask(Stream data);

        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "")]
       TaskInfo DisplayHelp();
    }

    public class TaskInfo
    {
        public string Help { get; set; }
    }

    public class TaskReceiver : ITaskReceiver
    {
        public string EnqueueTask(Stream data)
        {
            StreamReader reader = new StreamReader(data);
            string xmlString = reader.ReadToEnd();
            return  xmlString  ;
        }

        public TaskInfo DisplayHelp()
        {
            return new TaskInfo() { Help = "HTTP POST Task Xml as text/xml at this Url" };
        }
    }

Fielding HttpPost Requests with HttpListener 

static HttpListener m_Listener = null;


static public void RunServer()
        {
            var prefix = "http://localhost:8/Task/";
            // Note: There is also an Async approach to using HttpListener
            m_Listener = new HttpListener();
            m_Listener.Prefixes.Add(prefix);
            try
            {
                m_Listener.Start();
            }
            catch ()
            {
                return;
            }
            while (m_Listener.IsListening)
            {
                var context = m_Listener.GetContext();
                ProcessRequest(context);
            }
            m_Listener.Close();
        }

static private void ProcessRequest(HttpListenerContext context)
        {
            // Get the data from the HTTP stream
            var body = new StreamReader(context.Request.InputStream).ReadToEnd();

            byte[] b = Encoding.UTF8.GetBytes("ACK");
            context.Response.StatusCode = 200;
            context.Response.KeepAlive = false;
            context.Response.ContentLength64 = b.Length;

            var output = context.Response.OutputStream;
            output.Write(b, 0, b.Length);
            context.Response.Close();
        }