-
-
Save leonletto/10507344 to your computer and use it in GitHub Desktop.
Simple Windows WebServer for testing that ports are working
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### Basic webserver to check ports are available | |
## | |
## copy into a directory - for example c:\test | |
## open a command prompt and cd into that directory | |
## run 'powershell' - enter | |
## | |
## the first time you run powershell you will need to allow scripts to run | |
## to do this type 'Set-ExecutionPolicy UnRestricted' - enter | |
## | |
## Now type '.\powershell-web-server.ps1 2010' - enter | |
## This will start a web server on port 2010 which you can connect | |
## to if your firewall rules are correct. | |
## | |
## REMEMBER to run --Set-ExecutionPolicy Restricted-- when done your testing | |
## | |
## Enjoy! | |
## Leon | |
param ( | |
[string]$port = $(throw "-port is required.") | |
) | |
$myres1 = '<html><body>Server is accessible from port ' | |
$myres2 = '<br><a href="/end">Click here to Quit</a><BR>REMEMBER to run' | |
$myres3 = ' --Set-ExecutionPolicy Restricted-- when done your testing</body></html>' | |
$resp1 = $myres1 + $port + $myres2 + $myres3 | |
$myredir = '<html><head><meta http-equiv="refresh" content="0; url=/" /></head><body></body></html>' | |
$routes = @{ | |
"/" = { return $resp1 }; | |
"/end" = { return $myredir } | |
} | |
$url = "http://+:$port/" | |
$listener = New-Object System.Net.HttpListener | |
$listener.Prefixes.Add($url) | |
$listener.Start() | |
Write-Host "Listening at $url..." | |
while ($listener.IsListening) | |
{ | |
$context = $listener.GetContext() | |
$requestUrl = $context.Request.Url | |
$response = $context.Response | |
Write-Host '' | |
Write-Host "> $requestUrl" | |
$route = $routes.Get_Item($requestUrl.LocalPath) | |
if ($requestUrl.LocalPath -match '/end') { | |
$content = & $route | |
$buffer = [System.Text.Encoding]::UTF8.GetBytes($content) | |
$response.ContentLength64 = $buffer.Length | |
$response.OutputStream.Write($buffer, 0, $buffer.Length) | |
break | |
} | |
elseif ($route -eq $null) | |
{ | |
$response.StatusCode = 404 | |
} | |
else | |
{ | |
$content = & $route | |
$buffer = [System.Text.Encoding]::UTF8.GetBytes($content) | |
$response.ContentLength64 = $buffer.Length | |
$response.OutputStream.Write($buffer, 0, $buffer.Length) | |
} | |
$response.Close() | |
$responseStatus = $response.StatusCode | |
Write-Host "< $responseStatus" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment