C# HTTPServer和OrleansClient结合
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结合的更多相关文章
- NodeJS 最快速搭建一个HttpServer
最快速搭建一个HttpServer 在目录里放一个index.html cd D:\Web\InternalWeb start http-server -i -p 8081
- 基于Netty4的HttpServer和HttpClient的简单实现
Netty的主页:http://netty.io/index.html 使用的Netty的版本:netty-4.0.23.Final.tar.bz2 ‐ 15-Aug-2014 (Stable, Re ...
- libevent源码分析:http-server例子
http-server例子是libevent提供的一个简单web服务器,实现了对静态网页的处理功能. /* * gcc -g -o http-server http-server.c -levent ...
- httpserver
改了下 # -*- coding:utf-8 -*- from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler HOST = &quo ...
- 一个简单的零配置命令行HTTP服务器 - http-server (nodeJs)
http-server 是一个简单的零配置命令行HTTP服务器, 基于 nodeJs. 如果你不想重复的写 nodeJs 的 web-server.js, 则可以使用这个. 安装 (全局安装加 -g) ...
- nodejs搭建http-server
很多时候我们都需要搭建一个简单的服务器,部署在IIS,阿帕奇,或者用nodejs,网上很多关于nodejs搭建server的文章,但都是要创建server.js,很麻烦, 在这里我分享一个创建ht ...
- 一、HTTPServer,RequestHandler,ServerHandler,Handler
1. HTTPServer,RequestHandler,ServerHandler,Handler 1.1 基本概念 HTTPServer主要是对传输控制层HTTP,TCP,S ...
- nodejs:本地文件夹http服务器http-server
一.已经安装nodejs的电脑,有一个方便通过http访问本地文件夹.文件夹服务器 static files over HTTP,并不是我们平常说的node那个web服务器哦 二.好处 可以方便实现跨 ...
- PHP使用libevent实现高性能httpServer
今天发现php也有一个libevent的扩展,安装后尝试下了一个webserver(httpserver), 发现性能还不错,逻辑很简单,每秒响应速度1800~4000次/s 代码如下 <?ph ...
随机推荐
- 用 Prettier 统一团队的代码风格~
使用 prettier 自動調整 JavaScript 樣式 GFM 格式说明 为什么你不能缺少Linter(以及代码美化工具) 使用 prettier 自動調整 JavaScript 樣式 Reac ...
- Java字符串转16 进制工具类Hex.java
Java字符串转16 进制工具类Hex.java 学习了:https://blog.csdn.net/jia635/article/details/56678086 package com.strin ...
- HOW TO REPLACE ALL OCCURRENCES OF A CHARACTER IN A STD::STRING
From: http://www.martinbroadhurst.com/replacing-all-occurrences-of-a-character-in-a-stdstring.html T ...
- MDX Cookbook 08 - 基于集合上的迭代递归
递归的应用有时是非常重要的,特别在迭代一个集合的时候.为什么这么说呢?原因在于迭代在MDX中的使用是基于集合函数的,像 GENERATE() 它们都需要遍历整个集合.但是如果这个集合非常的庞大,我们仅 ...
- ORA-19602: cannot backup or copy active file in NOARCHIVELOG mode
备份数据库,报错如下 RMAN> backup database; Starting backup at -JAN- allocated channel: ORA_DISK_1 channel ...
- Retrofit 2.0 使用详细教程
文章来自:https://blog.csdn.net/carson_ho/article/details/73732076 前言 在Andrroid开发中,网络请求十分常用 而在Android网络请求 ...
- 设置response头信息禁止缓存
java代码中可通过如下代码设置 response.setHeader("Pragma", "No-Cache"); response.setHeader(&q ...
- SQL使用技巧
SQLServer 数据库变成单个用户后无法访问问题的解决方法 USE master; GO DECLARE @SQL VARCHAR(MAX); SET @SQL='' SELECT @SQL=@S ...
- CentOS7.4安装配置mysql8 TAR免安装版
下载mysql: https://dev.mysql.com/downloads/mysql/ 解压tar.xz文件:先 xz -d mysql-8.0.15-linux-glibc2.12-x86_ ...
- SNF快速开发平台MVC-富文本控件集成了百度开源项目editor
一.效果如下: 二.在框架当中调用代码如下: 1.在js里配置如下: <script type="text/javascript"> var viewModel =fu ...