Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Powershell HTTP server in background thread (could be easily killed)
$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
@MasterGroosha
Copy link

MasterGroosha commented Jan 1, 2016

Hangs on "Terminating" :(

@ASfSDlS61TLT6eoP3Qb7
Copy link

ASfSDlS61TLT6eoP3Qb7 commented Feb 16, 2016

Unfortunately, it indeed hangs on "Terminating..."

@ASfSDlS61TLT6eoP3Qb7
Copy link

ASfSDlS61TLT6eoP3Qb7 commented Feb 16, 2016

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" }

@natnael-wubet
Copy link

natnael-wubet commented Apr 19, 2017

if this is terminating, you should change the ports and dont forget to run it as administrator
to stop it just press ctrl+c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment