敲黑板:调试情况下请以管理员模型启动
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
public class MiniHttpServer
{
//以下数据来源于配置文件
private string comName = System.Configuration.ConfigurationManager.AppSettings["SerialPort"];//设置串口名称
public int port = int.Parse(ConfigurationManager.AppSettings.Get("HttpPort"));//http服务端口
public string prefix = ConfigurationManager.AppSettings.Get("HttpServer");//http服务地址,一般是本机IP地址
private HttpListener listerner;//http监听器
public bool IsStarted = false;//判断是否启动
SerialPort serialPort = new SerialPort();//定义一个串口
/// <summary>
/// 开始监听
/// </summary>
public void Start()
{
if (IsStarted) //已經再Listen就直接Return
return;
try
{
if (listerner == null)
listerner = new HttpListener();
listerner.AuthenticationSchemes = AuthenticationSchemes.
Anonymous;//指定身份验证Anonymous匿名访问
listerner.Prefixes.Add(prefix + ":" + port.ToString() + "/");
AddAddress(prefix + port.ToString() + "/");
listerner.Start();
IsStarted = true;
//以非同步方式取得Context
IAsyncResult result = this.listerner.BeginGetContext(new AsyncCallback(WebRequestCallback), this.listerner);
}
catch (Exception ex)
{
string errorMsg = ex.Message + (ex.InnerException != null ? ex.InnerException.Message : "");
}
}
/// <summary>
/// 停止监听
/// </summary>
public void Stop()
{
if (listerner != null)
{
listerner.Stop();
listerner.Close();
IsStarted = false;
}
}
/// <summary>
/// 处理请求
/// </summary>
/// <param name="result"></param>
private void WebRequestCallback(IAsyncResult result)
{
try
{
//如果Http Server已经停止不再理会
if (listerner == null)
return;
//取得Context
HttpListenerContext Context = this.listerner.EndGetContext(result);
//立即开始另一个非同步取得Context
listerner.BeginGetContext(new AsyncCallback(WebRequestCallback), this.listerner);
//处理我们的Web需求
ProcessRequest(Context);
}
catch (Exception ex)
{
string errorMsg = ex.Message + (ex.InnerException != null ? ex.InnerException.Message : "");
}
}
/// <summary>
/// 处理Web请求
/// </summary>
/// <param name="Context"></param>
private void ProcessRequest(System.Net.HttpListenerContext Context)
{
Encoding gb = System.Text.Encoding.GetEncoding("gb2312");
try
{
HttpListenerContext ctx = Context;
ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码
ctx.Response.AppendHeader("Access-Control-Allow-Origin", "*");//解决跨域问题
//假定LocalPath是192.168.0.1:8888/test,则会进入到第一个case中
switch (ctx.Request.Url.LocalPath)
{
case "/test":
//做你想要的操作
....
default:
setResponse(ctx, new ReturnInfo() { Code=-1,Msg="方法名错误!"});
break;
}
}
catch (Exception ex)
{
string errorMsg = ex.Message + (ex.InnerException != null ? ex.InnerException.Message : "");
}
}
/// <summary>
/// http请求返回
/// </summary>
/// <param name="Context"></param>
/// <param name="message"></param>
public void setResponse(HttpListenerContext Context, object message)
{
HttpListenerResponse Response = Context.Response;
Stream OutputStream = Response.OutputStream;
//產生回傳的Byte Array
byte[] bOutput = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(message));
//設定ContentType
Response.ContentType = "application/json; charset=utf-8";
//設定內容長度
Response.ContentLength64 = bOutput.Length;
//寫到Stream中
OutputStream.Write(bOutput, 0, bOutput.Length);
//關閉Stream
OutputStream.Close();
}
/// <summary>
/// 添加权限
/// </summary>
/// <param name="address"></param>
public static void AddAddress(string address)
{
AddAddress(address, Environment.UserDomainName, Environment.UserName);
}
/// <summary>
/// 添加运行权限
/// </summary>
/// <param name="address"></param>
/// <param name="domain"></param>
/// <param name="user"></param>
public static void AddAddress(string address, string domain, string user)
{
string argsDll = String.Format(@"http delete urlacl url={0}", address);
string args = string.Format(@"http add urlacl url={0} user={1}\{2}", address, domain, user);
ProcessStartInfo psi = new ProcessStartInfo("netsh", argsDll);
psi.Verb = "runas";
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
Process.Start(psi).WaitForExit();//删除urlacl
psi = new ProcessStartInfo("netsh", args);
psi.Verb = "runas";
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
Process.Start(psi).WaitForExit();//添加urlacl
}
}
调用方式:
MiniHttpServer httpserver = new MiniHttpServer();//本地httpserver服务
Thread httpThread = new Thread(new ParameterizedThreadStart(httpserver.Start));//启动服务
httpThread.Start();//传递当前打开的串口