HttpListener 监听HTTP 请求

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

namespace ConsoleAppHttpListener
{
/// <summary>
/// 监听HTTP 请求 By Rhythmk
/// </summary>
class Program
{
static void Main(string[] args)
{
ListenerHttpUrl();

Console.ReadKey();
}

static void ListenerHttpUrl()
{
string url = "http://admin2.rhytmk.t/rhythmk/";
using(HttpListener hListener=new HttpListener ())
{
// 匿名访问
hListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
hListener.Prefixes.Add(url);
//hListener.Prefixes.Add("url2")
hListener.Start();
Console.WriteLine(" ---Start---- ");
while (true)
{
HttpListenerContext hlContext = hListener.GetContext();
hlContext.Response.StatusCode = 200;
string Key = hlContext.Request.QueryString["key"];
if (!string.IsNullOrEmpty(Key))
{
Console.WriteLine(string.Format("The key is {0},Time : {1}",Key,DateTime.Now));
}
// 关闭请求
hlContext.Response.Close();

// 输出响应HTML 结构
//using (StreamWriter writer = new StreamWriter(hlContext.Response.OutputStream))
//{
// writer.WriteLine("true");
// writer.Close();
// hlContext.Response.Close();
//}
}
}
}

}
}

你可能感兴趣的:(listener)