using http_filetransfer; using Newtonsoft.Json; using Sodao.FastSocket.Server.Config; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using XImaging.Automation.Library.HxDriverLib; using XImaging.Automation.Service; namespace BiosenSocketService { public class BiosenHttpServer { 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 BiosenHttpServer() { } public static void Init() { PostServerSection section = ConfigurationManager.GetSection("fileServer") as PostServerSection; string server = section.Server.URI; string folder = ConfigurationManager.AppSettings.Get("UploadFolder"); string uploadPath = AppDomain.CurrentDomain.BaseDirectory + folder; if(!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } 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; }*/ } catch (Exception ex) { LogConstant.logger.Print("start httpserver exception:" + ex.ToString()); } //finally //{ // httplistener.Close(); //} } public static void Stop() { try { if (httplistener == null) return; httplistener.Close(); httplistener = null; } catch(Exception ex) { LogConstant.logger.Print("Stop():" + ex.ToString()); } } private static void Result(IAsyncResult ar) { //当接收到请求后程序流会走到这里 try { 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); } catch (Exception ex) { LogConstant.logger.Print("Stop():" + ex.ToString()); } } } /*public class PutCmd : IHttpCommand { public void Process(HttpListenerRequest request, ref HttpListenerResponse response) { string fullPath = BiosenHttpServer.ServerDirectory + request.RawUrl; try { string copyHeader = ConfigurationManager.AppSettings["Copy"]; var copyPath = request.Headers[copyHeader]; if (copyPath != null) { string tempPath = BiosenHttpServer.ServerDirectory + "/" + copyPath.TrimStart('/'); if (File.Exists(tempPath)) { File.Copy(tempPath, fullPath); } else { throw new DirectoryNotFoundException(); } } else { var dirname = Path.GetDirectoryName(fullPath); if (!Directory.Exists(dirname)) { Directory.CreateDirectory(dirname); } using (var newFile = new FileStream(fullPath, FileMode.OpenOrCreate)) { request.InputStream.CopyTo(newFile); } } } catch (FileNotFoundException) { response.StatusCode = BiosenHttpServer.NotFounded; } catch (DirectoryNotFoundException) { response.StatusCode = BiosenHttpServer.NotFounded; } catch (Exception ex) { response.StatusCode = BiosenHttpServer.NotFounded; Console.WriteLine(ex); } finally { response.OutputStream.Close(); } } } public class DeleteCmd : IHttpCommand { public void Process(HttpListenerRequest request, ref HttpListenerResponse response) { try { if (Directory.Exists(BiosenHttpServer.ServerDirectory + request.RawUrl)) Directory.Delete(BiosenHttpServer.ServerDirectory + request.RawUrl); else if (File.Exists(BiosenHttpServer.ServerDirectory + request.RawUrl)) File.Delete(BiosenHttpServer.ServerDirectory + request.RawUrl); } catch (FileNotFoundException) { response.StatusCode = BiosenHttpServer.NotFounded; } catch (DirectoryNotFoundException) { response.StatusCode = BiosenHttpServer.NotFounded; } catch (Exception) { response.StatusCode = BiosenHttpServer.BadRequest; } finally { response.OutputStream.Close(); } } } public class HeadCmd : IHttpCommand { public void Process(HttpListenerRequest request, ref HttpListenerResponse response) { string fullPath = BiosenHttpServer.ServerDirectory + request.RawUrl; try { var fileInfo = new FileInfo(fullPath); response.Headers.Add("Name", fileInfo.Name); response.Headers.Add("FileLength", fileInfo.Length.ToString()); response.Headers.Add("LastWriteTime", fileInfo.LastWriteTime.ToString("dd/MM/yyyy hh:mm")); } catch (FileNotFoundException) { response.StatusCode = BiosenHttpServer.NotFounded; } catch (DirectoryNotFoundException) { response.StatusCode = BiosenHttpServer.NotFounded; } catch (Exception) { response.StatusCode = BiosenHttpServer.NotFounded; } finally { response.OutputStream.Close(); } } }*/ 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, BiosenHttpServer.BufferSize); file.Close(); } else { var directories = Directory.EnumerateFiles(fullPath); foreach (var entry in directories) { writer.Write(JsonConvert.SerializeObject(entry)); } writer.Flush(); } } catch (FileNotFoundException) { response.StatusCode = BiosenHttpServer.NotFounded; } catch (DirectoryNotFoundException) { response.StatusCode = BiosenHttpServer.NotFounded; } catch { response.StatusCode = BiosenHttpServer.BadRequest; } finally { output.Close(); writer.Dispose(); } } } }