using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using GrainInterface;
using Newtonsoft.Json;
using Orleans; namespace PayServer
{
public class HttpServer
{
private const string NotFoundResponse = "<!doctype html><html><body>Resource not found</body></html>";
private readonly HttpListener httpListener;
private readonly CancellationTokenSource cts = new CancellationTokenSource();
private readonly string prefixPath; private Task processingTask; public HttpServer(string listenerUriPrefix)
{
this.prefixPath = ParsePrefixPath(listenerUriPrefix);
this.httpListener = new HttpListener();
this.httpListener.Prefixes.Add(listenerUriPrefix);
} private static string ParsePrefixPath(string listenerUriPrefix)
{
var match = Regex.Match(listenerUriPrefix, @"http://(?:[^/]*)(?:\:\d+)?/(.*)");
if (match.Success)
{
return match.Groups[].Value.ToLowerInvariant();
}
else
{
return string.Empty;
}
} public void Start()
{
this.httpListener.Start();
this.processingTask = Task.Factory.StartNew(async () => await ProcessRequests(), TaskCreationOptions.LongRunning);
} private async Task ProcessRequests()
{
while (!this.cts.IsCancellationRequested)
{
try
{
var context = await this.httpListener.GetContextAsync();
try
{
await ProcessRequest(context).ConfigureAwait(false);
context.Response.Close();
}
catch (Exception ex)
{
context.Response.StatusCode = ;
context.Response.StatusDescription = "Internal Server Error";
context.Response.Close();
Console.WriteLine("Error processing HTTP request\n{0}", ex);
}
}
catch (ObjectDisposedException ex)
{
if ((ex.ObjectName == this.httpListener.GetType().FullName) && (this.httpListener.IsListening == false))
{
return; // listener is closed/disposed
}
Console.WriteLine("Error processing HTTP request\n{0}", ex);
}
catch (Exception ex)
{
HttpListenerException httpException = ex as HttpListenerException;
if (httpException == null || httpException.ErrorCode != )// IO operation aborted
{
Console.WriteLine("Error processing HTTP request\n{0}", ex);
}
}
}
} private Task ProcessRequest(HttpListenerContext context)
{
if (context.Request.HttpMethod.ToUpperInvariant() != "GET")
{
return WriteNotFound(context);
} var urlPath = context.Request.RawUrl.Substring(this.prefixPath.Length)
.ToLowerInvariant(); switch (urlPath)
{
case "/":
if (!context.Request.Url.ToString().EndsWith("/"))
{
context.Response.Redirect(context.Request.Url + "/");
context.Response.Close();
return Task.FromResult();
}
else
{
return WriteString(context, "Hello World!", "text/plain");
}
case "/favicon.ico":
return WriteFavIcon(context);
case "/ping":
return WritePong(context);
case "/pay":
return OnPayResult(context);
}
return WriteNotFound(context);
} private static Task WritePong(HttpListenerContext context)
{
return WriteString(context, "pong", "text/plain");
} private static async Task OnPayResult(HttpListenerContext context)
{
var ret = "failed";
try
{
string postData;
using (var br = new BinaryReader(context.Request.InputStream))
{
postData =
Encoding.UTF8.GetString(
br.ReadBytes(int.Parse(context.Request.ContentLength64.ToString())));
}
if (!string.IsNullOrEmpty(postData))
{
Console.WriteLine("postData=[{0}]", postData); var request = JsonConvert.DeserializeObject<PayResult>(postData);
if (null != request)
{
var parmas = request.data.orderNo.Split(','); var id = long.Parse(parmas[]); var playerProxy = GrainClient.GrainFactory.GetGrain<IPlayerProxy>(id);
var success =
await playerProxy.OnPlayerPayResult(request.data.orderNo, request.code, request.msg);
if (success)
{
ret = "success";
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
} await WriteString(context, ret, "text/plain");
} private static async Task WriteFavIcon(HttpListenerContext context)
{
context.Response.ContentType = "image/png";
context.Response.StatusCode = ;
context.Response.StatusDescription = "OK";
using (var stream = File.Open("icon.png", FileMode.Open))
{
var output = context.Response.OutputStream;
await stream.CopyToAsync(output);
}
} private static Task WriteNotFound(HttpListenerContext context)
{
return WriteString(context, NotFoundResponse, "text/plain", , "NOT FOUND");
} private static async Task WriteString(HttpListenerContext context, string data, string contentType,
int httpStatus = , string httpStatusDescription = "OK")
{
AddCORSHeaders(context.Response);
AddNoCacheHeaders(context.Response); context.Response.ContentType = contentType;
context.Response.StatusCode = httpStatus;
context.Response.StatusDescription = httpStatusDescription; var acceptsGzip = AcceptsGzip(context.Request);
if (!acceptsGzip)
{
using (var writer = new StreamWriter(context.Response.OutputStream, Encoding.UTF8, , true))
{
await writer.WriteAsync(data).ConfigureAwait(false);
}
}
else
{
context.Response.AddHeader("Content-Encoding", "gzip");
using (GZipStream gzip = new GZipStream(context.Response.OutputStream, CompressionMode.Compress, true))
using (var writer = new StreamWriter(gzip, Encoding.UTF8, , true))
{
await writer.WriteAsync(data).ConfigureAwait(false);
}
}
} private static bool AcceptsGzip(HttpListenerRequest request)
{
string encoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(encoding))
{
return false;
} return encoding.Contains("gzip");
} private static void AddNoCacheHeaders(HttpListenerResponse response)
{
response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
response.Headers.Add("Pragma", "no-cache");
response.Headers.Add("Expires", "");
} private static void AddCORSHeaders(HttpListenerResponse response)
{
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
} private void Stop()
{
cts.Cancel();
if (processingTask != null && !processingTask.IsCompleted)
{
processingTask.Wait();
}
if (this.httpListener.IsListening)
{
this.httpListener.Stop();
this.httpListener.Prefixes.Clear();
}
} public void Dispose()
{
this.Stop();
this.httpListener.Close();
using (this.cts) { }
using (this.httpListener) { }
}
}
}

最新文章

  1. 学习微信小程序之css12设置盒子内容的宽高
  2. cmd光标移动
  3. UGUI&amp;&amp;Animator模块知识点随记
  4. textview滑动效果
  5. Android自带的theme
  6. flock — 轻便的咨询文件锁定
  7. 使用Jayrock开源组件开发基于JSON-RPC协议的接口
  8. iOS push与present Controller的区别
  9. AVPlayer的基本使用
  10. [python]倒计时实现
  11. codeforces #313 div1 D
  12. Unity3D--学习太空射击游戏制作(二)
  13. hdu 5637 BestCoder Round #74 (div.2)
  14. python:选房抽签小工具
  15. 【18】观察者模式(Observer Pattern)
  16. Luogu4606 SDOI2018 战略游戏 圆方树、虚树、链并
  17. Mysql 间隙锁原理,以及Repeatable Read隔离级别下可以防止幻读原理(百度)
  18. vue.js利用vue.router创建前端路由
  19. SOLR企业搜索平台 一 (搭建SOLR)
  20. 老师木发的makefile与autotools

热门文章

  1. ScrollView不能包含多个子项,ScrollView can host only one direct child
  2. Android四大组件应用系列5——使用AIDL实现跨进程调用Service
  3. Nginx软件优化
  4. 谷歌、亚马逊相继宣布屏蔽 Flash 广告,又一个时代行将结束?【转载+整理】
  5. linux下查看端口占用
  6. Linux中搭建一个ftp服务器详解
  7. 基于CentOS搭建私有云服务
  8. 【Android】Android传感器
  9. Swift 命令行输入输出
  10. 使用Nginx实现灰度发布(转)