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) { }
}
}
}

C# HTTPServer和OrleansClient结合的更多相关文章

  1. NodeJS 最快速搭建一个HttpServer

    最快速搭建一个HttpServer 在目录里放一个index.html cd D:\Web\InternalWeb start http-server -i -p 8081

  2. 基于Netty4的HttpServer和HttpClient的简单实现

    Netty的主页:http://netty.io/index.html 使用的Netty的版本:netty-4.0.23.Final.tar.bz2 ‐ 15-Aug-2014 (Stable, Re ...

  3. libevent源码分析:http-server例子

    http-server例子是libevent提供的一个简单web服务器,实现了对静态网页的处理功能. /* * gcc -g -o http-server http-server.c -levent ...

  4. httpserver

    改了下 # -*- coding:utf-8 -*- from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler HOST = &quo ...

  5. 一个简单的零配置命令行HTTP服务器 - http-server (nodeJs)

    http-server 是一个简单的零配置命令行HTTP服务器, 基于 nodeJs. 如果你不想重复的写 nodeJs 的 web-server.js, 则可以使用这个. 安装 (全局安装加 -g) ...

  6. nodejs搭建http-server

      很多时候我们都需要搭建一个简单的服务器,部署在IIS,阿帕奇,或者用nodejs,网上很多关于nodejs搭建server的文章,但都是要创建server.js,很麻烦, 在这里我分享一个创建ht ...

  7. 一、HTTPServer,RequestHandler,ServerHandler,Handler

    1.      HTTPServer,RequestHandler,ServerHandler,Handler 1.1       基本概念 HTTPServer主要是对传输控制层HTTP,TCP,S ...

  8. nodejs:本地文件夹http服务器http-server

    一.已经安装nodejs的电脑,有一个方便通过http访问本地文件夹.文件夹服务器 static files over HTTP,并不是我们平常说的node那个web服务器哦 二.好处 可以方便实现跨 ...

  9. PHP使用libevent实现高性能httpServer

    今天发现php也有一个libevent的扩展,安装后尝试下了一个webserver(httpserver), 发现性能还不错,逻辑很简单,每秒响应速度1800~4000次/s 代码如下 <?ph ...

随机推荐

  1. idea html,js修改不用重启进程

    1Setting -> build-compiler ---勾选  Build project automatically选项 2 快捷键Ctrl + Shift + A查找registry命令 ...

  2. Win7下MongoDB的安装和使用

    Win7下MongoDB的安装和使用 1.下载: http://www.mongodb.org/downloads 2.安装: 安装目录为 D:\mongodb\MongoDB 2.6 Standar ...

  3. python unknown error: DevToolsActivePort file doesn't exist 问题解决

    解决方案: from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_option ...

  4. .NET Unity XML 配置文件(2)

    本文内容 Unity 配置示意图 Unity 的 XML 架构 参考资料 研究配置文件总是很麻烦,而且很可能因为版本问题,会稍有不同.如果你不确定 Unity 是否支持以及如何支持某个元素,就看下相关 ...

  5. CentOS 6下 Oracle11gR2 设置开机自启动

    [1] 更改/etc/oratab # This file is used by ORACLE utilities. It is created by root.sh # and updated by ...

  6. Mongodb 笔记 - 性能及Java代码

    性能 以下数据都是在千兆网络下测试的结果 写入 数据量的增大会导致内存占满, 因为mongodb会将数据尽可能地载入内存, 索引占用的空间也很可观非安全模式下, 速度取决于内存是否占满能差一个数量级, ...

  7. IDEA环境设置

    设置SDK:https://blog.csdn.net/y999666/article/details/51893348 打开模板使用说明,找到Maven本地安装目录, 备份E:\Program Fi ...

  8. Atitit 列出wifi热点以及连接

    Atitit 列出wifi热点以及连接 配置命令 >netsh wlan  /?1 显示已经有的配置netsh wlan show profiles1 C:\Users\Administrato ...

  9. spring boot user authorities类图

  10. vue项目eslint环境配置与vscode配置eslint

    eslint基础环境搭建 全局安装eslint:npm install eslint -g 项目eslint初始化:eslint --init,按团队或自己的编程风格回答三道题. ? How woul ...