我将一个简单的本地服务器组合在一起,用于托管仅HTML的Web应用程序。我需要它是因为某些功能(例如AJAX请求)无法通过直接从文件系统打开的HTML使用。
看起来像这样并且可以正常工作。
# source: https://gist.github.com/19WAS85/5424431
$http = [System.Net.HttpListener]::new()
# Hostname and port to listen on
$http.Prefixes.Add("http://localhost:8080/")
# Start the Http Server
$http.Start()
Add-Type -AssemblyName System.Web
# Log ready message to terminal
if ($http.IsListening) {
write-host "HTTP Server Ready! " -f 'black' -b 'gre'
write-host "$($http.Prefixes)" -f 'y'
#write-host "then try going to $($http.Prefixes)other/path" -f 'y'
}
#New-PSDrive -Name MyPowerShellSite -PSProvider FileSystem -Root $PWD.Path
# INFINTE LOOP
# Used to listen for requests
while ($http.IsListening) {
# Get Request Url
# When a request is made in a web browser the GetContext() method will return a request object
# Our route examples below will use the request object properties to decide how to respond
$context = $http.GetContext()
if ($context.Request.HttpMethod -eq 'GET') {
# We can log the request to the terminal
write-host "$($context.Request.UserHostAddress) => $($context.Request.Url)" -f 'mag'
$URL = $context.Request.Url.LocalPath
# Redirect root to index.html
if($URL -eq "/") {
$URL = "/index.html"
}
$Content = Get-Content -Encoding Byte -Path "web/$URL"
$Context.Response.ContentType = [System.Web.MimeMapping]::GetMimeMapping("web/$URL")
$Context.Response.OutputStream.Write($Content, 0, $Content.Length)
$Context.Response.Close()
}
# powershell will continue looping and listen for new requests...
}
但是,请求要花费很长的时间。文件读取和写入输出流的方式有问题。
有修复程序吗?它是如此之慢,以至于基本上是没有用的。若要尝试,请确保在存在web/
子文件夹的地方运行它。例如,尝试打开照片可以轻松测试低速。
答案 0 :(得分:2)
密钥正在使用[System.IO.File]::OpenRead
生成流,然后将其直接读取的所有内容复制到套接字中,然后将其发送到浏览器。
这是整个Powershell本地目录HTTP服务器。如果要直接提供运行目录,请将"web/$URL"
更改为$URL
:
$http = [System.Net.HttpListener]::new()
# Hostname and port to listen on
$http.Prefixes.Add("http://localhost:8080/")
# Start the Http Server
$http.Start()
Add-Type -AssemblyName System.Web
# Log ready message to terminal
if ($http.IsListening) {
write-host "HTTP Server Ready! " -f 'black' -b 'gre'
write-host "$($http.Prefixes)" -f 'y'
}
# INFINTE LOOP
# Used to listen for requests
while ($http.IsListening) {
# Get Request Url
# When a request is made in a web browser the GetContext() method will return a request object
# Our route examples below will use the request object properties to decide how to respond
$context = $http.GetContext()
if ($context.Request.HttpMethod -eq 'GET') {
# We can log the request to the terminal
write-host "$($context.Request.UserHostAddress) => $($context.Request.Url)" -f 'mag'
$URL = $context.Request.Url.LocalPath
# Redirect root to index.html
if($URL -eq "/") {
$URL = "/index.html"
}
$ContentStream = [System.IO.File]::OpenRead( "web/$URL" );
$Context.Response.ContentType = [System.Web.MimeMapping]::GetMimeMapping("web/$URL")
$ContentStream.CopyTo( $Context.Response.OutputStream );
$Context.Response.Close()
}
# powershell will continue looping and listen for new requests...
}