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 e51f3c0 commit bbf61b7
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
51 changes: 51 additions & 0 deletions Pwsh/Web/Net.HttpListener Basics.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
function Log {
param(
[ArgumentCompletions('Listener', 'Response', 'Context', 'Other')]
[Parameter()]
$Who,
[ArgumentCompletions('ctor', 'Close', 'Start', 'End')]
[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:9090
' | write-host -fore red


Log Listener ctor
[Net.HttpListener]$Listen = @{}

$listen.Prefixes.add('http://localhost:9090/')

Log Listener Start
$Listen.Start()

Log Context ctor
$ctx = $Listen.GetContext()
$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 Other $Json
Log Context Write $byte_str.Length
$ctx.Response.OutputStream.Write( $byte_str, 0, $byte_str.Length )

Log Response Close
$ctx.Response.close()

Log Listener Close
$listen.Close()
Binary file added Pwsh/Web/img/Net.HttpListener-Basics.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 5 additions & 0 deletions Pwsh/Web/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## Web related scripts

- [Net.HttpListener Basics.ps1](Net.HttpListener%20Basics.ps1)

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

0 comments on commit bbf61b7

Please sign in to comment.