using System;
using System.Linq;
using System.Web;
namespace Shared.Net
{
public static class HttpListener
{
private static System.Net.HttpListener listener;
///
/// 启动监听及处理
///
public static void Start (System.Net.IPAddress ipAddress, int port)
{
try {
if (listener == null) {
listener = new System.Net.HttpListener ();
listener.AuthenticationSchemes = System.Net.AuthenticationSchemes.Anonymous;
listener.Prefixes.Add (string.Format ("http://{0}:{1}/", ipAddress.ToString (), port));
listener.Start ();
//beginGetContext(listener);
contextThread = new System.Threading.Thread (() => {
while (true) {
var context = listener.GetContext ();
System.Threading.Tasks.Task.Run (() => {
manager (context);
});
}
});
contextThread.Start ();
System.Console.WriteLine ("HttpListener已经启动!");
}
} catch (Exception e) {
System.Console.WriteLine ("HttpListener启动失败!\r\n" + e.Message);
}
}
///
///
///
static System.Threading.Thread contextThread;
///
/// 请求事件
///
/// 请求命令
/// 输出流
/// 输入流
public delegate void RequestEventHandler (System.Collections.Specialized.NameValueCollection nameValueCollection, System.IO.Stream outputStream, System.IO.Stream inputStream);
///
/// 请求事件
///
public static event RequestEventHandler EventHandler;
///
/// 开始异步接收http请求
///
///
private static void beginGetContext (System.Net.HttpListener listerner)
{
try {
if (listerner == null || !listerner.IsListening) {
return;
}
listerner.BeginGetContext (new System.AsyncCallback (getContextCallBack), null);
} catch {
System.Threading.Thread.Sleep (1);
beginGetContext (listerner);
}
}
///
/// 获取http请求,并处理
///
///
private static void getContextCallBack (System.IAsyncResult ar)
{
beginGetContext (listener);
try {
System.Net.HttpListenerContext context = listener.EndGetContext (ar);
manager (context);
} catch { }
}
///
/// 关闭
///
public static void Close ()
{
try {
if (contextThread != null) {
contextThread.Abort ();
contextThread = null;
}
} catch { }
try {
if (listener != null) {
listener.Close ();
listener = null;
}
} catch { }
System.Console.WriteLine ("HttpListener已经关闭!");
}
private static void manager (System.Net.HttpListenerContext httpListenerContext)
{
System.Net.HttpListenerResponse httpListenerResponse = null;
try {
#region
httpListenerResponse = httpListenerContext.Response;
httpListenerResponse.StatusCode = 200;//设置返回给客服端http状态代码
httpListenerResponse.ContentEncoding = System.Text.Encoding.UTF8;
if (EventHandler != null) {
EventHandler (HttpUtility.ParseQueryString (System.IO.Path.GetFileName (httpListenerContext.Request.RawUrl)), httpListenerResponse.OutputStream, httpListenerContext.Request.InputStream);
}
//string commandType = nameValueCollection.Get("CommandType");
//byte[] sendBytes = null;
//switch (commandType)
//{
// case "测试":
// Test("测试");
// sendBytes = System.Text.Encoding.UTF8.GetBytes("测试成功");
// break;
// default:
// sendBytes = System.Text.Encoding.UTF8.GetBytes("指令暂时不支持");
// break;
//}
//stream.Write(sendBytes, 0, sendBytes.Length);
httpListenerResponse.OutputStream.Flush ();
#endregion
} catch {
} finally {
#region
try {
httpListenerContext.Request.InputStream.Close ();
} catch { }
try {
httpListenerResponse.OutputStream.Close ();
} catch { }
try {
httpListenerResponse.Close ();
} catch { }
#endregion
}
}
private static void Test (string text)
{
//System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(System.IO.Path.Combine(File.RootPath,"Hello.txt"));
//streamWriter.WriteLine(text);
//streamWriter.Close();
System.Console.WriteLine ("HttpListener 接收到测试信息!");
}
public static void PostData (string url, string postJson)
{
System.IO.Stream outputStream = null;
System.IO.Stream inputStream = null;
try {
System.Net.HttpWebRequest webReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create (new Uri (url));
webReq.Method = "POST";
//webReq
byte [] byteData = System.Text.Encoding.UTF8.GetBytes (postJson);
//定义传送数据格式
webReq.ContentType = "application/json";
webReq.Accept = "application/json";
//webReq.ContentType = "application/x-www-form-urlencoded";
//webReq.Timeout = 1000*2;
webReq.ContentLength = byteData.Length;
//定义Stream信息
outputStream = webReq.GetRequestStream ();
outputStream.Write (byteData, 0, byteData.Length);
outputStream.Flush ();
outputStream.Close ();
//inputStream= webReq.GetResponse().GetResponseStream();
} catch {
throw new Exception ("发送失败");
} finally {
if (null != outputStream) {
outputStream.Close ();
}
if (null != inputStream) {
inputStream.Close ();
}
}
}
}
}