原文 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. java线程池框架源代码分析

    相关类Executor,Executors.AbstractExecutorService.ExecutorService Executor:整个线程池运行者框架的顶层接口. 定义了一个execute ...

  2. 毕设一:python 爬取苏宁的商品评论

    毕设需要大量的商品评论,网上找的数据比较旧了,自己动手 代理池用的proxypool,github:https://github.com/jhao104/proxy_pool ua:fake_user ...

  3. 80. Domino Internet Password

    Internet口令保存在Domino文件夹的个人文档的HTTPPassword域中,和文档中的username一起用于藉各种Internet协议訪问Dominoserver时的校验,最经常使用的就是 ...

  4. JVM参数调优:Eclipse启动实践

    本文主要参考自<深入理解 Java 虚拟机>.这本书是国人写的难得的不是照搬代码注释的且不是废话连篇的技术书,内容涵盖了 Java 从源码到字节码到执行的整个过程,包括了 JVM(Java ...

  5. vista/win7系统 红警/CS/星际争霸 局域网连接方法

    昨晚,闲来无事,忽然想起打红警来,于是和宿舍舍友商量一起联机打红警, 可是在win7下不能联机红警,网上很多人都这么说,昨晚我折腾了2小时,终于解决了这个问题. win7系统是可以联机打红警的!!!! ...

  6. VS2015如何自定义类模板、我的模板——原来这么简单!

    在前一段时间忽然想给自己电脑上的vs新建类的时候添加一个自定义个注释,但是在网上搜了很久都是说vs2012之类的方法系统也都是win7.XP之类的独独没有win8的.故此自己不断的尝试修改发现方法如下 ...

  7. 开源软件的许可(License)

    自由软件基金会(Free Software Foundation):FSF 0. GNU GNU (GNU is Not Unix 的递归缩写)计划,又称革奴计划,是由 Richard Stallma ...

  8. 详尽分析世纪之战:360VS腾讯是两个阶层的抗争

    很不错的一篇文字  分析的也很透彻 [转自中国移动http://labs.chinamobile.com/] 来源:搜狐IT 作者:吃熊掌的鱼 2010-11-01 10:11:51 [ 13967阅 ...

  9. 窗体的基类中没有设定大小,所以才不能居中,若要窗体居中,必须使用setfixedsize()函数或者resize()函数设定窗体的大小,居中才能正常使用

    最近开发中,遇到了窗体不能居中的问题,看了网上的很多文章,窗口居中,无非都是move至窗口的中心目标; 有两种方式, 一种在构造函数中直接计算中心坐标; 另一种是在窗口show后再move至相应坐标. ...

  10. ASP.NET Core 基础教程-约定 - ASP.NET Core 基础教程 - 简单教程,简单编程

    原文:ASP.NET Core 基础教程-约定 - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core 基础教程-约定 因为 ASP.NET Core 是可以跨平台的 ...