I am creating an HTTPListener that will execute some code with data that is POST to the URI the script is listening to:
$timeout = New-Timespan -Minutes 10
$sw = [Diagnostics.Stopwatch]::StartNew()
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add('http://+:8912/')
while ($sw.elapsed -lt $timeout) {
$listener.Start()
$context = $listener.GetContext()
$request = $context.Request
$response = $context.Response
$InputStream = New-Object System.IO.StreamReader $Context.Request.InputStream
# $msg = $InputStream.ReadToEnd() | ConvertFrom-Json
if ($request.Url -match '/post$') {
$response.ContentType = 'application/json'
# $msg | Write-Output
$message = "Message Received"
$raw = $InputStream.ReadToEnd()
$raw | Write-Output
$raw | Out-file -FilePath C:\msg.json
}
if ($request.Url -match '/end$') { break }
[byte[]] $buffer = [System.Text.Encoding]::UTF8.GetBytes($message)
$response.ContentLength64 = $buffer.Length
$output = $response.OutputStream
$output.Write($buffer, 0, $buffer.Length)
$output.Close()
}
$listener.Stop()
The problem that I'm running into is that the listener won't terminate and continue the script even when $sw.elapsed -lt $timeout
is $false
.
Is there a way I can make the listener terminate after 10 minutes and continue the script?