2013年5月30日 星期四

C# HttpListener 範例

建立Console專案.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpListener listener = new HttpListener();
            try
            {
                listener.Prefixes.Add("http://*:8055/"); //要監聽的URL範圍
                listener.Start(); //開始監聽端口,接收客户端請求
                Console.WriteLine("Listening");
                while (true)
                {
                    //獲取一個客户端請求為止
                    HttpListenerContext context = listener.GetContext();
                    //將其處理過程放入線程池(Pool)
                    System.Threading.ThreadPool.QueueUserWorkItem(ProcessHttpClient, context);
                }
            }
            catch (Exception e)
            {

                Console.WriteLine(e.Message);
            }
            finally
            {
                listener.Stop(); //關閉HttpListener
            }
        }

        //客户請求處理
        static void ProcessHttpClient(object obj)
        {
            HttpListenerContext context = obj as HttpListenerContext;
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;
            //string s = request.QueryString["command"];
            //do something as you want
            string responseString = string.Format(" {0}", DateTime.Now);
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);

            //關閉輸出流,釋放相應資源。
            output.Close();
        }
    }
}




沒有留言:

張貼留言