原文 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. 二维高斯滤波器(gauss filter)的实现

    我们以一个二维矩阵表示二元高斯滤波器,显然此二维矩阵的具体形式仅于其形状(shape)有关: def gauss_filter(kernel_shape): 为实现二维高斯滤波器,需要首先定义二元高斯 ...

  2. Erlang学习笔记2

    http://wgcode.iteye.com/blog/1007623 第二章 入门 1.所有的变量都必须以大写字母开头,如果要查看某个变量,只要输入变量的名字即可,如果一个变量被赋予值,就称为绑定 ...

  3. 【t054】糟糕的网络

    Time Limit: 1 second Memory Limit: 128 MB [问题描述] 前几天sqybi 还在高高兴兴的用BOINC 完成着一个又一个的任务呢,但现在sqybi 突然变得闷闷 ...

  4. BZOJ 1369 Gem - 树型dp

    传送门 题目大意: 给一棵树上每个点一个正权值,要求父子的权值不同,问该树的最小权值和是多少. 题目分析: 证不出来最少染色数,那就直接信仰用20来dp吧:dp[u][i]表示u节点权值赋为i时u子树 ...

  5. 一题多解(五) —— topK(数组中第 k 大/小的数)

    根据对称性,第 k 大和第 k 小,在实现上,是一致的,我们就以第 k 小为例,进行说明: 法 1 直接排序(sort(A, A+N)),当使用一般时间复杂度的排序算法时,其时间复杂度为 O(N2) ...

  6. 【codeforces 787B】Not Afraid

    [题目链接]:http://codeforces.com/contest/787/problem/B [题意] -水题..题目太吓人 [题解] 只要你在一组里面找到两个数字,它们的绝对值相同,但是正负 ...

  7. 【t045】细菌

    Time Limit: 1 second Memory Limit: 128 MB [问题描述] 近期,农场出现了D (1<= D <=15)种细菌.John 要从他的 N (1<= ...

  8. IWXAPI的使用,发布分享和支付

    今天看代码,看到以前项目的微信支付功能,想做一下记录 首先是在application类里面定义 public static IWXAPI MSGAPI; public static final Str ...

  9. 【35.56%】【727A】Transformation: from A to B

    time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...

  10. 用js获取实时的获取当前的年月日,时分秒,以及星期

    <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="C ...