C# HTTPServer和OrleansClient结合

1using System; 2using System.Collections.Generic; 3using System.IO; 4using System.IO.Compression; 5using System.Linq; 6using System.Net; 7using System.Text; 8using System.Text.RegularExpressions; 9using System.Threading; 10using System.Threading.Tasks; 11using GrainInterface; 12using Newtonsoft.Json; 13using Orleans; 14 15namespace PayServer 16{ 17 public class HttpServer 18 { 19 private const string NotFoundResponse = "<!doctype html><html><body>Resource not found</body></html>"; 20 private readonly HttpListener httpListener; 21 private readonly CancellationTokenSource cts = new CancellationTokenSource(); 22 private readonly string prefixPath; 23 24 private Task processingTask; 25 26 public HttpServer(string listenerUriPrefix) 27 { 28 this.prefixPath = ParsePrefixPath(listenerUriPrefix); 29 this.httpListener = new HttpListener(); 30 this.httpListener.Prefixes.Add(listenerUriPrefix); 31 } 32 33 private static string ParsePrefixPath(string listenerUriPrefix) 34 { 35 var match = Regex.Match(listenerUriPrefix, @"http://(?:[^/]*)(?:\:\d+)?/(.*)"); 36 if (match.Success) 37 { 38 return match.Groups[1].Value.ToLowerInvariant(); 39 } 40 else 41 { 42 return string.Empty; 43 } 44 } 45 46 public void Start() 47 { 48 this.httpListener.Start(); 49 this.processingTask = Task.Factory.StartNew(async () => await ProcessRequests(), TaskCreationOptions.LongRunning); 50 } 51 52 private async Task ProcessRequests() 53 { 54 while (!this.cts.IsCancellationRequested) 55 { 56 try 57 { 58 var context = await this.httpListener.GetContextAsync(); 59 try 60 { 61 await ProcessRequest(context).ConfigureAwait(false); 62 context.Response.Close(); 63 } 64 catch (Exception ex) 65 { 66 context.Response.StatusCode = 500; 67 context.Response.StatusDescription = "Internal Server Error"; 68 context.Response.Close(); 69 Console.WriteLine("Error processing HTTP request\n{0}", ex); 70 } 71 } 72 catch (ObjectDisposedException ex) 73 { 74 if ((ex.ObjectName == this.httpListener.GetType().FullName) && (this.httpListener.IsListening == false)) 75 { 76 return; // listener is closed/disposed 77 } 78 Console.WriteLine("Error processing HTTP request\n{0}", ex); 79 } 80 catch (Exception ex) 81 { 82 HttpListenerException httpException = ex as HttpListenerException; 83 if (httpException == null || httpException.ErrorCode != 995)// IO operation aborted 84 { 85 Console.WriteLine("Error processing HTTP request\n{0}", ex); 86 } 87 } 88 } 89 } 90 91 private Task ProcessRequest(HttpListenerContext context) 92 { 93 if (context.Request.HttpMethod.ToUpperInvariant() != "GET") 94 { 95 return WriteNotFound(context); 96 } 97 98 var urlPath = context.Request.RawUrl.Substring(this.prefixPath.Length) 99 .ToLowerInvariant(); 100 101 switch (urlPath) 102 { 103 case "/": 104 if (!context.Request.Url.ToString().EndsWith("/")) 105 { 106 context.Response.Redirect(context.Request.Url + "/"); 107 context.Response.Close(); 108 return Task.FromResult(0); 109 } 110 else 111 { 112 return WriteString(context, "Hello World!", "text/plain"); 113 } 114 case "/favicon.ico": 115 return WriteFavIcon(context); 116 case "/ping": 117 return WritePong(context); 118 case "/pay": 119 return OnPayResult(context); 120 } 121 return WriteNotFound(context); 122 } 123 124 private static Task WritePong(HttpListenerContext context) 125 { 126 return WriteString(context, "pong", "text/plain"); 127 } 128 129 private static async Task OnPayResult(HttpListenerContext context) 130 { 131 var ret = "failed"; 132 try 133 { 134 string postData; 135 using (var br = new BinaryReader(context.Request.InputStream)) 136 { 137 postData = 138 Encoding.UTF8.GetString( 139 br.ReadBytes(int.Parse(context.Request.ContentLength64.ToString()))); 140 } 141 if (!string.IsNullOrEmpty(postData)) 142 { 143 Console.WriteLine("postData=[{0}]", postData); 144 145 var request = JsonConvert.DeserializeObject<PayResult>(postData); 146 if (null != request) 147 { 148 var parmas = request.data.orderNo.Split(','); 149 150 var id = long.Parse(parmas[0]); 151 152 var playerProxy = GrainClient.GrainFactory.GetGrain<IPlayerProxy>(id); 153 var success = 154 await playerProxy.OnPlayerPayResult(request.data.orderNo, request.code, request.msg); 155 if (success) 156 { 157 ret = "success"; 158 } 159 } 160 } 161 } 162 catch (Exception e) 163 { 164 Console.WriteLine(e); 165 } 166 167 await WriteString(context, ret, "text/plain"); 168 } 169 170 private static async Task WriteFavIcon(HttpListenerContext context) 171 { 172 context.Response.ContentType = "image/png"; 173 context.Response.StatusCode = 200; 174 context.Response.StatusDescription = "OK"; 175 using (var stream = File.Open("icon.png", FileMode.Open)) 176 { 177 var output = context.Response.OutputStream; 178 await stream.CopyToAsync(output); 179 } 180 } 181 182 private static Task WriteNotFound(HttpListenerContext context) 183 { 184 return WriteString(context, NotFoundResponse, "text/plain", 404, "NOT FOUND"); 185 } 186 187 private static async Task WriteString(HttpListenerContext context, string data, string contentType, 188 int httpStatus = 200, string httpStatusDescription = "OK") 189 { 190 AddCORSHeaders(context.Response); 191 AddNoCacheHeaders(context.Response); 192 193 context.Response.ContentType = contentType; 194 context.Response.StatusCode = httpStatus; 195 context.Response.StatusDescription = httpStatusDescription; 196 197 var acceptsGzip = AcceptsGzip(context.Request); 198 if (!acceptsGzip) 199 { 200 using (var writer = new StreamWriter(context.Response.OutputStream, Encoding.UTF8, 4096, true)) 201 { 202 await writer.WriteAsync(data).ConfigureAwait(false); 203 } 204 } 205 else 206 { 207 context.Response.AddHeader("Content-Encoding", "gzip"); 208 using (GZipStream gzip = new GZipStream(context.Response.OutputStream, CompressionMode.Compress, true)) 209 using (var writer = new StreamWriter(gzip, Encoding.UTF8, 4096, true)) 210 { 211 await writer.WriteAsync(data).ConfigureAwait(false); 212 } 213 } 214 } 215 216 217 private static bool AcceptsGzip(HttpListenerRequest request) 218 { 219 string encoding = request.Headers["Accept-Encoding"]; 220 if (string.IsNullOrEmpty(encoding)) 221 { 222 return false; 223 } 224 225 return encoding.Contains("gzip"); 226 } 227 228 private static void AddNoCacheHeaders(HttpListenerResponse response) 229 { 230 response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate"); 231 response.Headers.Add("Pragma", "no-cache"); 232 response.Headers.Add("Expires", "0"); 233 } 234 235 private static void AddCORSHeaders(HttpListenerResponse response) 236 { 237 response.Headers.Add("Access-Control-Allow-Origin", "*"); 238 response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 239 } 240 241 private void Stop() 242 { 243 cts.Cancel(); 244 if (processingTask != null && !processingTask.IsCompleted) 245 { 246 processingTask.Wait(); 247 } 248 if (this.httpListener.IsListening) 249 { 250 this.httpListener.Stop(); 251 this.httpListener.Prefixes.Clear(); 252 } 253 } 254 255 public void Dispose() 256 { 257 this.Stop(); 258 this.httpListener.Close(); 259 using (this.cts) { } 260 using (this.httpListener) { } 261 } 262 } 263}
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )