using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.Http; namespace Admin.Core.Socket.Plugins { /// /// 支持GET、Post、Put,Delete,或者其他 /// internal class MyHttpPlug : HttpPluginBase { protected override void OnGet(HttpSocketClient client, HttpContextEventArgs e) { if (e.Context.Request.UrlEquals("/success")) { //直接响应文字 e.Context.Response.FromText("Success").Answer();//直接回应 Console.WriteLine("处理完毕"); e.Handled = true; } else if (e.Context.Request.UrlEquals("/file")) { //直接回应文件。 e.Context.Response .SetStatus()//必须要有状态 .FromFile(@"D:\System\Windows.iso", e.Context.Request); } else if (e.Context.Request.UrlEquals("/html")) { //回应html StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(""); stringBuilder.AppendLine(""); stringBuilder.AppendLine(""); stringBuilder.AppendLine(""); stringBuilder.AppendLine("TouchSocket"); stringBuilder.AppendLine(""); stringBuilder.AppendLine(""); stringBuilder.AppendLine("
"); stringBuilder.AppendLine("王二麻子"); stringBuilder.AppendLine(""); stringBuilder.AppendLine(""); stringBuilder.AppendLine("
"); stringBuilder.AppendLine(""); stringBuilder.AppendLine(""); e.Context.Response .SetStatus()//必须要有状态 .SetContentTypeByExtension(".html") .SetContent(stringBuilder.ToString()); e.Context.Response.Answer(); } base.OnGet(client, e); } protected override void OnPost(HttpSocketClient client, HttpContextEventArgs e) { if (e.Context.Request.UrlEquals("/uploadfile")) { try { if (e.Context.Request.TryGetContent(out byte[] bodys))//一次性获取请求体 { return; } while (true)//当数据太大时,可持续读取 { byte[] buffer = new byte[1024 * 64]; int r = e.Context.Request.Read(buffer, 0, buffer.Length); if (r == 0) { return; } //这里可以一直处理读到的数据。 } //下面逻辑是接收小文件。 if (e.Context.Request.ContentLen > 1024 * 1024 * 100)//全部数据体超过100Mb则直接拒绝接收。 { e.Context.Response .SetStatus("403", "数据过大") .Answer(); return; } //此操作会先接收全部数据,然后再分割数据。 //所以上传文件不宜过大,不然会内存溢出。 var multifileCollection = e.Context.Request.GetMultifileCollection(); foreach (var item in multifileCollection) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append($"文件名={item.FileName}\t"); stringBuilder.Append($"数据长度={item.Length}"); client.Logger.Info(stringBuilder.ToString()); } e.Context.Response .SetStatus() .FromText("Ok") .Answer(); } catch (Exception ex) { client.Logger.Exception(ex); } } base.OnPost(client, e); } } }