Skip to content

Commit df13f4e

Browse files
author
James Brundage
committed
feat: Get-WebSocket -Broadcast ( Fixes #39 )
1 parent 4926a83 commit df13f4e

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

Commands/Get-WebSocket.ps1

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,9 @@ function Get-WebSocket {
161161
[int]
162162
$BufferSize = 64kb,
163163

164+
[PSObject]
165+
$Broadcast,
166+
164167
# The ScriptBlock to run after connection to a websocket.
165168
# This can be useful for making any initial requests.
166169
[ScriptBlock]
@@ -771,6 +774,7 @@ function Get-WebSocket {
771774
} else {
772775
if ($existingJob -and -not $Force) {
773776
$httpListenerJob = $existingJob
777+
$httpListener = $existingJob.HttpListener
774778
} else {
775779
$httpListenerJob = Start-ThreadJob -ScriptBlock $SocketServerJob -Name "$RootUrl" -InitializationScript $InitializationScript -ArgumentList $Variable
776780
}
@@ -783,7 +787,33 @@ function Get-WebSocket {
783787
)
784788
}
785789
$httpListenerJob
786-
}
790+
}
791+
792+
if ($Broadcast) {
793+
if (-not $httpListener.SocketRequests) {
794+
Write-Warning "No WebSocket connections to broadcast to."
795+
} else {
796+
if ($broadcast -is [byte[]]) {
797+
$broadcast = [ArraySegment[byte]]::new($broadcast)
798+
}
799+
if ($broadcast -is [System.ArraySegment[byte]]) {
800+
foreach ($socketRequest in $httpListener.SocketRequests.Values) {
801+
$socketRequest.WebSocket.SendAsync($broadcast, 'Binary', 'EndOfMessage', [Threading.CancellationToken]::None)
802+
}
803+
}
804+
else {
805+
foreach ($broadcastItem in $Broadcast) {
806+
$broadcastJson = ConvertTo-Json -InputObject $broadcastItem
807+
$broadcastJsonBytes = $OutputEncoding.GetBytes($broadcastJson)
808+
$broadcastSegment = [ArraySegment[byte]]::new($broadcastJsonBytes)
809+
foreach ($socketRequest in $httpListener.SocketRequests.Values) {
810+
$socketRequest.WebSocket.SendAsync($broadcastSegment, 'Text', 'EndOfMessage', [Threading.CancellationToken]::None)
811+
}
812+
}
813+
}
814+
}
815+
816+
}
787817
}
788818

789819
# If `-Debug` was passed,

0 commit comments

Comments
 (0)