A simple in-process HTTP server for UWP
原文 http://www.dzhang.com/blog/2012/09/18/a-simple-in-process-http-server-for-windows-8-metro-apps
简单来说,就是在UWP中做一个支持GET请求简单的Web Server,本实例UWP(server) 与 Winform(client) 在同一机子将无法通讯,但UWP(server)写client代码可调用调试。
注意,Package.appxmanifest 选项“功能”卡中的Internet配置。
Below is some code for a simple HTTP server for Metro/Modern-style Windows 8 apps. This code supports GET requests for a resource located at the root-level (e.g. http://localhost:8000/foo.txt) and looks for the corresponding file in the Data directory of the app package. This might be useful for unit testing, among other things.
public class HttpServer : IDisposable {
private const uint BufferSize = ;
private static readonly StorageFolder LocalFolder
= Windows.ApplicationModel.Package.Current.InstalledLocation;
private readonly StreamSocketListener listener;
public HttpServer(int port) {
this.listener = new StreamSocketListener();
this.listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket);
this.listener.BindServiceNameAsync(port.ToString());
}
public void Dispose() {
this.listener.Dispose();
}
private async void ProcessRequestAsync(StreamSocket socket) {
// this works for text only
StringBuilder request = new StringBuilder();
using(IInputStream input = socket.InputStream) {
byte[] data = new byte[BufferSize];
IBuffer buffer = data.AsBuffer();
uint dataRead = BufferSize;
while (dataRead == BufferSize) {
await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
request.Append(Encoding.UTF8.GetString(data, , data.Length));
dataRead = buffer.Length;
}
}
using (IOutputStream output = socket.OutputStream) {
string requestMethod = request.ToString().Split('\n')[];
string[] requestParts = requestMethod.Split(' ');
if (requestParts[] == "GET")
await WriteResponseAsync(requestParts[], output);
else
throw new InvalidDataException("HTTP method not supported: "
+ requestParts[]);
}
}
private async Task WriteResponseAsync(string path, IOutputStream os) {
using (Stream resp = os.AsStreamForWrite()) {
bool exists = true;
try {
// Look in the Data subdirectory of the app package
string filePath = "Data" + path.Replace('/', '\\');
using (Stream fs = await LocalFolder.OpenStreamForReadAsync(filePath)) {
string header = String.Format("HTTP/1.1 200 OK\r\n" +
"Content-Length: {0}\r\n" +
"Connection: close\r\n\r\n",
fs.Length);
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await resp.WriteAsync(headerArray, , headerArray.Length);
await fs.CopyToAsync(resp);
}
}
catch (FileNotFoundException) {
exists = false;
}
if (!exists) {
byte[] headerArray = Encoding.UTF8.GetBytes(
"HTTP/1.1 404 Not Found\r\n" +
"Content-Length:0\r\n" +
"Connection: close\r\n\r\n");
await resp.WriteAsync(headerArray, , headerArray.Length);
}
await resp.FlushAsync();
}
}
}
Usage:
const int port = ;
using (HttpServer server = new HttpServer(port)) {
using (HttpClient client = new HttpClient()) {
try {
byte[] data = await client.GetByteArrayAsync(
"http://localhost:" + port + "/foo.txt");
// do something with
}
catch (HttpRequestException) {
// possibly a 404
}
}
}
Notes:
- The app manifest needs to declare the "Internet (Client & Server)" and/or the "Private Networks (Client & Server)" capability.
- Due to the Windows 8 security model:
- A Metro app can access network servers within its own process.
- A Metro app Foo can access network servers hosted by another Metro app Bar iff Foo has a loopback exemption. You can use
CheckNetIsolation.exeto do this. This is useful for debugging only, as it must be done manually. - A Desktop app cannot access network servers hosted by a Metro app. The
BackgroundDownloaderappears to fall into this category even though that is an API available to Metro apps.
A simple in-process HTTP server for UWP的更多相关文章
- a simple erlang process pool analysis
a simple erlang process pool analysis 这是一个简单的erlang进程池分析,是learn you some erlang for Great Good 里面的一个 ...
- [Docker] Build a Simple Node.js Web Server with Docker
Learn how to build a simple Node.js web server with Docker. In this lesson, we'll create a Dockerfil ...
- Simple TCP/IP Echo Server & Client Application in C#
1. TCP Server The server’s job is to set up an endpoint for clients to connect to and passively wait ...
- TCP/UDP server
Simple: Sample TCP/UDP server https://msdn.microsoft.com/en-us/library/aa231754(v=vs.60).aspx Simple ...
- npm start a http server( 在windows的任意目录上开启一个http server 用来测试html 页面和js代码,不用放到nginx的webroot目录下!!)
原文:https://stackabuse.com/how-to-start-a-node-server-examples-with-the-most-popular-frameworks/#:~:t ...
- 理解SQL Server的查询内存授予(译)
此文描述查询内存授予(query memory grant)在SQL Server上是如何工作的,适用于SQL 2005 到2008. 查询内存授予(下文缩写为QMG)是用于存储当数据进行排序和连接时 ...
- mysql启动不成功显示The server quit without updating PID file的解决方法
上午在编译安装mysql的时候 就出现标题中的错误,经实践在第二步操作后启动成功,参考链接 链接http://linuxadministrator.pro/blog/?p=225 You may fa ...
- SMTP Failed on Process Scheduler
If you are seeing messages like this in your message log when running a process through the process ...
- 转贴: A Simple c# Wrapper for ffMpeg
原帖地址:http://jasonjano.wordpress.com/2010/02/09/a-simple-c-wrapper-for-ffmpeg/ A Simple c# Wrapper fo ...
随机推荐
- ts demuxer的加入记录
文件夹 1 初衷 2 ts demux的功能介绍 1 初衷 之前打算给dtplayer加入一些亮点功能,最初的想法是:bt下载播放 + hls支持 bt下载因为以来libtorrent库,尽管搞懂了怎 ...
- Unity UGUI——Rect Transform包(Anchors)
Anchors(锚)操作演示 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvTXJfQUhhbw==/font/5a6L5L2T/fontsize/400/ ...
- node与webpack的process.env.NODE_ENV
先看两篇文章 1.前端工程项目的NODE_ENV 2. Node 环境变量 process.env.NODE_ENV 之webpack应用 3.process.env.NODE_ENV 下面全部是在w ...
- window.url.createobjecturl 兼容多种浏览器(IE,google,360,Safari,firefox)
<script type="text/javascript"> function setImagePreview() { var docObj = document.g ...
- Hibernate——(3)主键生成方式
一.Hibernate中常用的主键生成方式有如下几种: 1)identity: 用于自动生成主键方式,除了 Oracle 不支持,其他数据库一般都支持(较常用) 2)sequence: Oracle ...
- Linux socket编程示例(最简单的TCP和UDP两个例子)
一.socket编程 网络功能是Uinux/Linux的一个重要特点,有着悠久的历史,因此有一个非常固定的编程套路. 基于TCP的网络编程: 基于连接, 在交互过程中, 服务器和客户端要保持连接, 不 ...
- 在动态THML语句中调用JS函数传递带空格参数的问题
刚刚遇到一个问题,调用js函数的参数里带空格,造成调用失败的问题. 部分代码如下: html+="<div><a href=javascript:confirm(&qu ...
- windown下linux子系统的安装和卸载
原文:windown下linux子系统的安装和卸载 安装 第一步 打开开发人员模式 第二步 勾选适用linux的window子系统 第三步 打开powershell 第四步 在PowerShe ...
- 线性滤波器(linear filter)与非线性滤波器(non-linear filter)
1. 均值滤波器与中值滤波器 image processing - Difference between linear and non linear filter - Signal Processin ...
- C++学习笔记26,虚函数
在C++里面,虚拟功能是功能的一类重要!不同目的可以通过在不同的虚拟功能来达到同样的动作被定义. 举一个简单的例子: #include <iostream> #include <st ...