class Program
{
static void Main(string[] args)
{
string port = "8080";
HttpListener httpListener = new HttpListener();
httpListener.Prefixes.Add(string.Format("http://+:{0}/", port));
httpListener.Start();
httpListener.BeginGetContext(new AsyncCallback(GetContext), httpListener); //开始异步接收request请求
Console.WriteLine("监听端口:" + port);
Console.Read();
}
static void GetContext(IAsyncResult ar)
{
HttpListener httpListener = ar.AsyncState as HttpListener;
HttpListenerContext context = httpListener.EndGetContext(ar); //接收到的请求context(一个环境封装体)
httpListener.BeginGetContext(new AsyncCallback(GetContext), httpListener); //开始 第二次 异步接收request请求
HttpListenerRequest request = context.Request; //接收的request数据
HttpListenerResponse response = context.Response; //用来向客户端发送回复
response.ContentType = "html";
response.ContentEncoding = Encoding.UTF8;
using (Stream output = response.OutputStream) //发送回复
{
byte[] buffer = Encoding.UTF8.GetBytes("要返回的内容");
output.Write(buffer, 0, buffer.Length);
}
}
}
/// <summary>
/// MIME类型
/// </summary>
public Dictionary<string, string> MIME_Type = new Dictionary<string, string>()
{
{ "htm", "text/html" },
{ "html", "text/html" },
{ "php", "text/html" },
{ "xml", "text/xml" },
{ "json", "application/json" },
{ "txt", "text/plain" },
{ "js", "application/x-javascript" },
{ "css", "text/css" },
{ "bmp", "image/bmp" },
{ "ico", "image/ico" },
{ "png", "image/png" },
{ "gif", "image/gif" },
{ "jpg", "image/jpeg" },
{ "jpeg", "image/jpeg" },
{ "webp", "image/webp" },
{ "zip", "application/zip"},
{ "*", "*/*" }
};
/// <summary>
/// 启动本地网页服务器
/// </summary>
/// <param name="webroot">网站根目录</param>
/// <returns></returns>
public bool Start(string webroot)
{
//触发事件
if (OnServerStart != null)
OnServerStart(httpListener);
WebRoot = webroot;
try
{
//监听端口
httpListener.Prefixes.Add("http://+:" + port.ToString() + "/");
httpListener.Start();
httpListener.BeginGetContext(new AsyncCallback(onWebResponse), httpListener); //开始异步接收request请求
}
catch (Exception ex)
{
Qdb.Error(ex.Message, QDebugErrorType.Error, "Start");
return false;
}
return true;
}
/// <summary>
/// 网页服务器相应处理
/// </summary>
/// <param name="ar"></param>
private void onWebResponse(IAsyncResult ar)
{
byte[] responseByte = null; //响应数据
HttpListener httpListener = ar.AsyncState as HttpListener;
HttpListenerContext context = httpListener.EndGetContext(ar); //接收到的请求context(一个环境封装体)
httpListener.BeginGetContext(new AsyncCallback(onWebResponse), httpListener); //开始 第二次 异步接收request请求
//触发事件
if (OnGetRawContext != null)
OnGetRawContext(context);
HttpListenerRequest request = context.Request; //接收的request数据
HttpListenerResponse response = context.Response; //用来向客户端发送回复
//触发事件
if (OnGetRequest != null)
OnGetRequest(request, response);
if (rawUrl == "" || rawUrl == "/") //单纯输入域名或主机IP地址
fileName = WebRoot + @"\index.html";
else if (rawUrl.IndexOf('.') == -1) //不带扩展名,理解为文件夹
fileName = WebRoot + @"\" + rawUrl.SubString(1) + @"\index.html";
else
{
int fileNameEnd = rawUrl.IndexOf('?');
if (fileNameEnd > -1)
fileName = rawUrl.Substring(1, fileNameEnd - 1);
fileName = WebRoot + @"\" + rawUrl.Substring(1);
}
//处理请求文件名的后缀
string fileExt = Path.GetExtension(fileName).Substring(1);
if (!File.Exists(fileName))
{
responseByte = Encoding.UTF8.GetBytes("404 Not Found!");
response.StatusCode = (int)HttpStatusCode.NotFound;
}
else
{
try
{
responseByte = File.ReadAllBytes(fileName);
response.StatusCode = (int)HttpStatusCode.OK;
}
catch (Exception ex)
{
Qdb.Error(ex.Message, QDebugErrorType.Error, "onWebResponse");
response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
}
if (MIME_Type.ContainsKey(fileExt))
response.ContentType = MIME_Type[fileExt];
else
response.ContentType = MIME_Type["*"];
response.Cookies = request.Cookies; //处理Cookies
response.ContentEncoding = Encoding.UTF8;
using (Stream output = response.OutputStream) //发送回复
{
try
{
output.Write(responseByte, 0, responseByte.Length);
}
catch (Exception ex)
{
Qdb.Error(ex.Message, QDebugErrorType.Error, "onWebResponse");
response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
}
}
/// <summary>
/// 是否开启PHP功能
/// </summary>
public bool PHP_CGI_Enabled = true;
/// <summary>
/// PHP执行文件路径
/// </summary>
public string PHP_CGI_Path = "php-cgi";
接下来在网页服务的核心代码里做PHP支持的处理。
//PHP处理
string phpCgiOutput = "";
Action phpProc = new Action(() =>
{
try
{
string argStr = "";
if (request.HttpMethod == "GET")
{
if (rawUrl.IndexOf('?') > -1)
argStr = rawUrl.Substring(rawUrl.IndexOf('?'));
}
else if (request.HttpMethod == "POST")
{
using (StreamReader reader = new StreamReader(request.InputStream))
{
argStr = reader.ReadToEnd();
}
}
Process p = new Process();
p.StartInfo.CreateNoWindow = false; //不显示窗口
p.StartInfo.RedirectStandardOutput = true; //重定向输出
p.StartInfo.RedirectStandardInput = false; //重定向输入
p.StartInfo.UseShellExecute = false; //是否指定操作系统外壳进程启动程序
p.StartInfo.FileName = PHP_CGI_Path;
p.StartInfo.Arguments = string.Format("-q -f {0} {1}", fileName, argStr);
p.Start();
StreamReader sr = p.StandardOutput;
while (!sr.EndOfStream)
{
phpCgiOutput += sr.ReadLine() + Environment.NewLine;
}
responseByte = sr.CurrentEncoding.GetBytes(phpCgiOutput);
}
catch (Exception ex)
{
Qdb.Error(ex.Message, QDebugErrorType.Error, "onWebResponse->phpProc");
response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
});
if (fileExt == "php" && PHP_CGI_Enabled)
{
phpProc();
}
else
{
if (!File.Exists(fileName))
{
responseByte = Encoding.UTF8.GetBytes("404 Not Found!");
response.StatusCode = (int)HttpStatusCode.NotFound;
}
else
{
try
{
responseByte = File.ReadAllBytes(fileName);
response.StatusCode = (int)HttpStatusCode.OK;
}
catch (Exception ex)
{
Qdb.Error(ex.Message, QDebugErrorType.Error, "onWebResponse");
response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有