Skip to content

Instantly share code, notes, and snippets.

@nobodyguy
Last active July 9, 2022 15:09
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save nobodyguy/9950375 to your computer and use it in GitHub Desktop.
Save nobodyguy/9950375 to your computer and use it in GitHub Desktop.
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
@ASfSDlS61TLT6eoP3Qb7
Copy link

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

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

@mark05e
Copy link

mark05e commented Jul 9, 2022

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