Multiple Listeners
Serve the same routes on more than one port / interface.
Prerequisites: see Introduction.
Full source
File: pwsh/tutorial/examples/7.2-Multiple-Listeners.ps1
<#
Sample Kestrun Server - Multiple Listeners
Demonstrates adding multiple HTTP listeners for the same server instance.
FileName: 7.2-Multiple-Listeners.ps1
#>
param(
[int]$Port = 5000,
[IPAddress]$IPAddress = [IPAddress]::Loopback
)
# (Optional) Configure console logging
New-KrLogger |
Add-KrSinkConsole |
Register-KrLogger -Name 'console' -SetAsDefault | Out-Null
$Port2 = $Port + 433
# Create a new Kestrun server
New-KrServer -Name 'Endpoints Multi'
# Loopback listener on primary port
Add-KrEndpoint -Port $Port -IPAddress $IPAddress
# Second loopback listener on secondary port
Add-KrEndpoint -Port $Port2 -IPAddress $IPAddress
# Add the PowerShell runtime
# Enable Kestrun configuration
Enable-KrConfiguration
# Map a simple ping route
Add-KrMapRoute -Verbs Get -Pattern '/ping' -ScriptBlock {
Write-KrLog -Level Debug -Message 'Ping requested'
Write-KrTextResponse -InputObject 'pong' -StatusCode 200
}
Write-KrLog -Level Information -Message 'Multiple listeners configured ({Port}, {Port2})' -Values $Port, $Port2
# Start the server asynchronously
Start-KrServer -CloseLogsOnExit
Step-by-step
- Create server.
- Add first listener: 5000 loopback.
- Add second listener: 6000 loopback.
- Add PowerShell runtime and commit config.
- Register one
/pingroute (shared by all listeners). - Start server.
Try it
curl http://127.0.0.1:5000/ping
curl http://127.0.0.1:6000/ping
Invoke-WebRequest -Uri http://127.0.0.1:5000/ping | Select-Object -ExpandProperty Content
Invoke-WebRequest -Uri http://127.0.0.1:6000/ping | Select-Object -ExpandProperty Content
Both return pong.
References
- New-KrServer
- Add-KrEndpoint
- Enable-KrConfiguration
- Add-KrMapRoute
- Start-KrServer
- Write-KrTextResponse
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| One port works, other fails | Port already bound | Choose free port |
| Route works on first only | Config enabled before second listener | Add all listeners before Enable-KrConfiguration |
Previous / Next
Go back to Basic Server or continue to HTTPS & Certificates.