using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Web; using XCommon.Log; namespace XHandler.Class { public class HttpServer { public static int BufferSize = 8192; public const string DeleteMethod = "DELETE"; public const int NotFounded = 404; public const int BadRequest = 400; public const int NotImplemented = 501; private static HttpListener httplistener; public HttpServer() { } /// /// 创建文件 /// /// 路径 /// 内容 public static void CreateFileContent(string path, string content) { if (!string.IsNullOrEmpty(content)) { UTF8Encoding utf8 = new UTF8Encoding(true); FileInfo fi = new FileInfo(path); var di = fi.Directory; if (!di.Exists) { di.Create(); } StreamWriter sw = new StreamWriter(path, false, utf8); sw.Write(content); sw.Close(); } } public static string GetLocalIP() { try { string HostName = Dns.GetHostName(); //得到主机名 IPHostEntry IpEntry = Dns.GetHostEntry(HostName); for (int i = 0; i < IpEntry.AddressList.Length; i++) { //从IP地址列表中筛选出IPv4类型的IP地址 //AddressFamily.InterNetwork表示此IP为IPv4, //AddressFamily.InterNetworkV6表示此地址为IPv6类型 if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork) { return IpEntry.AddressList[i].ToString(); } } return ""; } catch (Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); return ""; } } //获取ip public static string GetIP() { string result = String.Empty; if (HttpContext.Current != null && HttpContext.Current.Session != null && HttpContext.Current.Session["IP"] != null) { result = HttpContext.Current.Session["IP"].ToString(); } else { result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (null == result || result == String.Empty) { result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } if (null == result || result == String.Empty) { result = HttpContext.Current.Request.UserHostAddress; } //if (null == result || result == String.Empty || !IsIP(result)) //{ // return "0.0.0.0"; //} } return result; } /// /// 初始化地址 /// /// IP /// 端口 /// 文件名 /// 内容 public static string Init(string ip, string port, string fileName, string content) { string server = $"http://{ip}:{port}/"; //string server = "http://localhost:8081/"; string folder = "UploadFolder"; string uploadPath = AppDomain.CurrentDomain.BaseDirectory + folder; if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } string pathStr = uploadPath + "\\" + fileName; CreateFileContent(pathStr, content); httplistener = new HttpListener(); try { httplistener.Prefixes.Add(server); httplistener.Start(); Console.WriteLine("server successfully runned"); httplistener.BeginGetContext(Result, null); //LogConstant.logger.Print("[httpserver =]" + server + " 已启动"); /*while (true) { IHttpCommand command; HttpListenerContext httplistenercontext = httplistener.GetContext(); string commandname = httplistenercontext.Request.HttpMethod; }*/ return server + folder + "/" + fileName; } catch (Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); //LogConstant.logger.Print("start httpserver exception:" + ex.ToString()); } //finally //{ // httplistener.Close(); //} return ""; } public static void Stop() { httplistener.Close(); httplistener = null; } private static void Result(IAsyncResult ar) { //当接收到请求后程序流会走到这里 if (httplistener == null) return; //继续异步监听 httplistener.BeginGetContext(Result, null); var guid = Guid.NewGuid().ToString(); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"接到新的请求:{guid},时间:{DateTime.Now.ToString()}"); //获得context对象 var context = httplistener.EndGetContext(ar); var request = context.Request; var response = context.Response; //如果是js的ajax请求,还可以设置跨域的ip地址与参数 //context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//后台跨域请求,通常设置为配置文件 //context.Response.AppendHeader("Access-Control-Allow-Headers", "ID,PW");//后台跨域参数设置,通常设置为配置文件 //context.Response.AppendHeader("Access-Control-Allow-Method", "post");//后台跨域请求设置,通常设置为配置文件 context.Response.ContentType = "text/plain;charset=UTF-8";//告诉客户端返回的ContentType类型为纯文本格式,编码为UTF-8 context.Response.AddHeader("Content-type", "text/plain");//添加响应头信息 context.Response.ContentEncoding = Encoding.UTF8; string returnObj = null;//定义返回客户端的信息 IHttpCommand command = null; string commandname = request.HttpMethod; switch (commandname) { /*case WebRequestMethods.Http.Put: command = new PutCmd(); Console.WriteLine("method PUT was called"); break; case DeleteMethod: command = new DeleteCmd(); Console.WriteLine("method DELETE was called"); break; case WebRequestMethods.Http.Head: command = new HeadCmd(); Console.WriteLine("method HEAD was called"); break;*/ case WebRequestMethods.Http.Get: command = new GetCmd(); Console.WriteLine("method GET was called"); break; default: Console.WriteLine("Unrecognized Method!"); response.StatusCode = NotImplemented; response.OutputStream.Close(); break; } if (command != null) command.Process(request, ref response); } } public class GetCmd : IHttpCommand { public void Process(HttpListenerRequest request, ref HttpListenerResponse response) { Stream output = response.OutputStream; var writer = new StreamWriter(output); string subPath = request.RawUrl.Substring(1); subPath = subPath.Replace('/', '\\'); string fullPath = AppDomain.CurrentDomain.BaseDirectory + subPath; try { if (File.Exists(fullPath)) { Stream file = new FileStream(fullPath, FileMode.Open); file.CopyTo(output, HttpServer.BufferSize); file.Close(); } else { var directories = Directory.EnumerateFiles(fullPath); foreach (var entry in directories) { writer.Write(JsonConvert.SerializeObject(entry)); } writer.Flush(); } } catch (FileNotFoundException ex) { LoggerHelper.ErrorLog("ERROR:", ex); response.StatusCode = HttpServer.NotFounded; } catch (DirectoryNotFoundException ex) { LoggerHelper.ErrorLog("ERROR:", ex); response.StatusCode = HttpServer.NotFounded; } catch { response.StatusCode = HttpServer.BadRequest; } finally { output.Close(); writer.Dispose(); } } } }