Skip to content

Commit

Permalink
added Http listener demo
Browse files Browse the repository at this point in the history
  • Loading branch information
ninmonkey committed Dec 18, 2023
1 parent bbf61b7 commit b3648b8
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Pwsh/Web/Net.HttpListener Basics.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,10 @@ $ctx.Response.close()

Log Listener Close
$listen.Close()

<#
for async,
$task = $httpListener.GetContextAsync()
while (-not $task.AsyncWaitHandle.WaitOne(200)) { }
$context = $task.GetAwaiter().GetResult()
#>
58 changes: 58 additions & 0 deletions Pwsh/Web/Net.HttpListener Part2 Async Cancel.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
function Log {
param(
[ArgumentCompletions('Listener', 'Response', 'Context', 'Other', 'Task')]
[Parameter()]
$Who,
[ArgumentCompletions('ctor', 'Close', 'Start', 'End', 'Wait', 'Sleep')]
[Parameter()]
$What,
[Parameter()]
$Message = ''
)
$Color = switch ($Who) {
'Listener' { 'lightblue' }
'Context' { 'lightgreen' }
'Response' { 'orange' }
default { 'darkyellow' }
}
"${Who}::${What} ${Message}" | Write-Host -bg $Color -fg black
}

'tip: Open a new window and run
> irm http://localhost:9092
' | write-host -fore red

if( $listen.IsListening ) {
throw 'nope'
# or
$Listen.Dispose()
$Listen = $Null
}

[Net.HttpListener]$Listen = @{}
$listen.Prefixes.add('http://localhost:9098/')
$Listen.Start()

Log Task Start 'Async Wait'
$task = $Listen.GetContextAsync()
try {
while ( -not $Task.AsyncWaitHandle.WaitOne(200)) {
Log Task Sleep 'tick 200ms'
}
$ctx = $task.GetAwaiter().GetResult()
$ctx.Response.StatusCode = 200
$ctx.Response.ContentType = 'text/html'

$message = 'hi world 🐒 !'
$byte_str = [Text.Encoding]::UTF8.GetBytes( $message )
$json = ($ctx.Response | ConvertTo-Json -wa 0 -Depth 0 -Compress)
Log Response Write $json
$ctx.Response.OutputStream.Write( $byte_str, 0, $byte_str.Length )

} finally {
Log Response Close
Log Listen Close
$ctx.Response.Dispose()
$listen.Dispose()
}
1 change: 1 addition & 0 deletions Pwsh/Web/readme.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## Web related scripts

- [Net.HttpListener Basics.ps1](Net.HttpListener%20Basics.ps1)
- [Net.HttpListener AsyncWait And Safe Cancelation](./Net.HttpListener%20Part2%20Async%20Cancel.ps1)

![screenshot](./img/Net.HttpListener-Basics.png)

0 comments on commit b3648b8

Please sign in to comment.