Last active
July 9, 2022 15:09
-
-
Save nobodyguy/9950375 to your computer and use it in GitHub Desktop.
Powershell HTTP server in background thread (could be easily killed)
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
$ServerThreadCode = { | |
$listener = New-Object System.Net.HttpListener | |
$listener.Prefixes.Add('http://+:8008/') | |
$listener.Start() | |
while ($listener.IsListening) { | |
$context = $listener.GetContext() # blocks until request is received | |
$request = $context.Request | |
$response = $context.Response | |
$message = "Testing server" | |
# This will terminate the script. Remove from production! | |
if ($request.Url -match '/end$') { break } | |
[byte[]] $buffer = [System.Text.Encoding]::UTF8.GetBytes($message) | |
$response.ContentLength64 = $buffer.length | |
$response.StatusCode = 500 | |
$output = $response.OutputStream | |
$output.Write($buffer, 0, $buffer.length) | |
$output.Close() | |
} | |
$listener.Stop() | |
} | |
$serverJob = Start-Job $ServerThreadCode | |
Write-Host "Listening..." | |
Write-Host "Press Ctrl+C to terminate" | |
[console]::TreatControlCAsInput = $true | |
# Wait for it all to complete | |
while ($serverJob.State -eq "Running") | |
{ | |
if ([console]::KeyAvailable) { | |
$key = [system.console]::readkey($true) | |
if (($key.modifiers -band [consolemodifiers]"control") -and ($key.key -eq "C")) | |
{ | |
Write-Host "Terminating..." | |
$serverJob | Stop-Job | |
Remove-Job $serverJob | |
break | |
} | |
} | |
Start-Sleep -s 1 | |
} | |
# Getting the information back from the jobs | |
Get-Job | Receive-Job |
Unfortunately, it indeed hangs on "Terminating..."
I managed to stop the listener by a little dirty way:
try { $result = Invoke-WebRequest -Uri "http://localhost:888/end" } catch { Write-Host "Listener ended" }
if this is terminating, you should change the ports and dont forget to run it as administrator
to stop it just press ctrl+c
Made minor changes to include @ASfSDlS61TLT6eoP3Qb7 suggestions.
https://gist.github.com/mark05e/089b6668895345dd274fe5076f8e1271
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hangs on "Terminating" :(