原文 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.exe to 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 BackgroundDownloader appears to fall into this category even though that is an API available to Metro apps.

A simple in-process HTTP server for UWP的更多相关文章

  1. a simple erlang process pool analysis

    a simple erlang process pool analysis 这是一个简单的erlang进程池分析,是learn you some erlang for Great Good 里面的一个 ...

  2. [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 ...

  3. 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 ...

  4. TCP/UDP server

    Simple: Sample TCP/UDP server https://msdn.microsoft.com/en-us/library/aa231754(v=vs.60).aspx Simple ...

  5. 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 ...

  6. 理解SQL Server的查询内存授予(译)

    此文描述查询内存授予(query memory grant)在SQL Server上是如何工作的,适用于SQL 2005 到2008. 查询内存授予(下文缩写为QMG)是用于存储当数据进行排序和连接时 ...

  7. mysql启动不成功显示The server quit without updating PID file的解决方法

    上午在编译安装mysql的时候 就出现标题中的错误,经实践在第二步操作后启动成功,参考链接 链接http://linuxadministrator.pro/blog/?p=225 You may fa ...

  8. SMTP Failed on Process Scheduler

    If you are seeing messages like this in your message log when running a process through the process ...

  9. 转贴: A Simple c# Wrapper for ffMpeg

    原帖地址:http://jasonjano.wordpress.com/2010/02/09/a-simple-c-wrapper-for-ffmpeg/ A Simple c# Wrapper fo ...

随机推荐

  1. 【SSH2(理论+实践)】--图说Struts2的执行

        前几篇文章讨论了有关Struts2的核心机制及一些基础,但同一时候也遗留下了非常多问题.这些问题主要是针对Struts2的一些使用技巧的,该篇文章将会针对Struts2的使用技巧进行讨论, ...

  2. erlang app 文件

    http://hje.iteye.com/blog/1211734 应用的概念¶ 当我们写了实现特定功能的代码之后,我们可能想将代码转成一个 应用 (application),这是可以作为一个单元启动 ...

  3. 【NOIP2012提高组】国王游戏 贪心 + 高精度

    题目分析 题目答案不具有单调性,所以不可以二分,转而思考贪心.因为无法确定位置,所以考虑如何才能让对于每一个$1 ~ i$使得$i$的答案最大,即$1 ~ i$最后一个最优.若设对于位置$i$,$a[ ...

  4. win32命令行小程序获取指定文件夹或者目录下面的所有文件大小,文件数量,目录数量

    #include <Windows.h> #include <stdio.h> #include <tchar.h> LARGE_INTEGER       lgA ...

  5. Android——四大组件、六大布局、五大存储

    一.android四大组件 (一)android四大组件详解 Android四大组件分别为activity.service.content provider.broadcast receiver. 1 ...

  6. 聊聊QPS/TPS/并发量/系统吞吐量的概念

    原文:聊聊QPS/TPS/并发量/系统吞吐量的概念 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/cainiao_user/article/deta ...

  7. 利用WPF建立自己的3d gis软件(非axhost方式)(三)矢量数据显示控制

    原文:利用WPF建立自己的3d gis软件(非axhost方式)(三)矢量数据显示控制 先下载SDK:https://pan.baidu.com/s/1M9kBS6ouUwLfrt0zV0bPew 密 ...

  8. postman VS restlet client基本使用

    postman与restlet都是使用的google浏览器的插件(出不去自行解决,you get!),此两款软件的强大这里就不在赘述了,postman的网上说明很多,restlet的中文配置很少了.这 ...

  9. 一篇简单易懂的原理文章,让你把JVM玩弄与手掌之中

    jvm原理 Java虚拟机是整个java平台的基石,是java技术实现硬件无关和操作系统无关的关键环节,是java语言生成极小体积的编译代码的运行平台,是保护用户机器免受恶意代码侵袭的保护屏障.JVM ...

  10. Android中使用ListView实现自适应表格

    GridView比ListView更容易实现自适应的表格,但是GridView每个格单元的大小固定,而ListView实现的表格可以自定义每个格单元的大小,但因此实现自适应表格也会复杂些(格单元大小不 ...