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中做一个简单的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 = 8192;
  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, 0, data.Length));
        dataRead = buffer.Length;
      }
    }

    using (IOutputStream output = socket.OutputStream) {
      string requestMethod = request.ToString().Split(‘\n‘)[0];
      string[] requestParts = requestMethod.Split(‘ ‘);

      if (requestParts[0] == "GET")
        await WriteResponseAsync(requestParts[1], output);
      else
        throw new InvalidDataException("HTTP method not supported: "
                                       + requestParts[0]);
    }
  }

  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, 0, 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, 0, headerArray.Length);
      }

      await resp.FlushAsync();
    }
  }
}

Usage:

const int port = 8000;
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.
时间: 2024-07-28 16:42:21

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 里面的一个example,详细的内容可到官网查看! 主要的流程图 实现原理 这个的例子的实现原理官网都有比较详细的说明,主要模块在ppool_serv中,ppool_serv是一个gen_server behaviour, 而ppool_sup 是一个one_for_all的策略,如果ppool_serv或者

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

此文描述查询内存授予(query memory grant)在SQL Server上是如何工作的,适用于SQL 2005 到2008. 查询内存授予(下文缩写为QMG)是用于存储当数据进行排序和连接时的临时中间数据行.查询在实际执行前需要先请求保留内存,所以会存在一个授予的动作. 这样的好处是提高查询的可靠性和避免单个查询占用所有的内存. SQL Server在收到查询时,会执行3个被定义好的步骤来返回用户所请求的结果集. 1.生成编译计划.它包括各种逻辑指令,如怎么联接数据行. 2.生成执行计

How to Kill All Processes That Have Open Connection in a SQL Server Database[关闭数据库链接 最佳方法] -摘自网络

SQL Server database administrators may frequently need in especially development and test environments  instead of the production environments to kill all the open connections to a  specific database in order to process SQL Server maintenance task ov

SQL 2012群集添加节点失败“Please wait while Microsoft SQL Server 2012 Service Pack 1 Setup processes

问题描述(Issue Symptoms) SQL Server 2012 STD cluster安装在Windows Server 2012时,添加节点时,在以下界面超过4小时无法通过: "Please wait while Microsoft SQL Server 2012 Service Pack 1 Setup processes the current operation." 第二天存在以下界面,但是无法选择已经安装的群集 原因分析(Cause) 1. 查看了安装日志发现 De

《Pro SQL Server Internals》部分翻译(P36-P45)

本文选自<Pro SQL Server Internals> 作者: Dmitri Korotkevitch 出版社: Apress 出版年: 2016-12-29 作者简介:Dmitri Korotkevitchis是微软SQL Server MVP和微软认证大师.作为应用程序和数据库开发人员.数据库管理员和数据库架构师,他具有多年使用SQL Server的经验.他专门从事OLTP系统在高负载下的设计.开发和性能调优.Dmitri经常在各种Microsoft和SQL PASS活动上发言,他为

《Pro SQL Server Internals》翻译之索引

本文选自<Pro SQL Server Internals> 作者: Dmitri Korotkevitch 出版社: Apress 出版年: 2016-12-29 页数: 804 作者简介:Dmitri Korotkevitchis是微软SQL Server MVP和微软认证大师.作为应用程序和数据库开发人员.数据库管理员和数据库架构师,他具有多年使用SQL Server的经验.他专门从事OLTP系统在高负载下的设计.开发和性能调优.Dmitri经常在各种Microsoft和SQL PASS

http-server: a command-line http server

http-server https://github.com/http-party/http-server#readme http-server is a simple, zero-configuration command-line http server. It is powerful enough for production usage, but it's simple and hackable enough to be used for testing, local developme

Permissible Privileges for GRANT and REVOKE

Table 6.2 Permissible Privileges for GRANT and REVOKE Privilege Column Context ALL [PRIVILEGES] Synonym for "all privileges" Server administration ALTER Alter_priv Tables ALTER ROUTINE Alter_routine_priv Stored routines CREATE Create_priv Databa

ansible及ansible-palybook使用(持续更新)

一.简介 Ansible is a radically simple configuration-management, application deployment, task-execution, and multinode orchestration engine. Design Principles Have a dead simple setup process and a minimal learning curve Be super fast & parallel by defau