|
| 1 | +<# |
| 2 | +.SYNOPSIS |
| 3 | + Sends a WebSocket message. |
| 4 | +.DESCRIPTION |
| 5 | + Sends a message from a WebSocket server. |
| 6 | +#> |
| 7 | +param( |
| 8 | +[PSObject] |
| 9 | +$Message, |
| 10 | + |
| 11 | +[string] |
| 12 | +$Pattern |
| 13 | +) |
| 14 | + |
| 15 | +function sendMessage { |
| 16 | + param([Parameter(ValueFromPipeline)]$msg, [PSObject[]]$Sockets) |
| 17 | + process { |
| 18 | + if ($msg -is [byte[]]) { |
| 19 | + $messageSegment = [ArraySegment[byte]]::new($msg) |
| 20 | + foreach ($socket in $sockets) { |
| 21 | + if ($null -ne $messageSegment -and $socket.SendAsync) { |
| 22 | + $null = $socket.SendAsync($messageSegment, 'Binary', 'EndOfMessage',[Threading.Cancellationtoken]::None) |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + } else { |
| 27 | + $jsonMessage = ConvertTo-Json -InputObject $msg |
| 28 | + $messageSegment = [ArraySegment[byte]]::new($OutputEncoding.GetBytes($jsonMessage)) |
| 29 | + foreach ($socket in $sockets) { |
| 30 | + if ($null -ne $messageSegment -and $socket.SendAsync) { |
| 31 | + $null = $socket.SendAsync($messageSegment, 'Binary', 'EndOfMessage',[Threading.Cancellationtoken]::None) |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + $msg |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +$patternAsRegex = $pattern -as [regex] |
| 40 | +$socketList = @( |
| 41 | + foreach ($socketConnection in $this.HttpListener.SocketRequests.Values) { |
| 42 | + if ( |
| 43 | + $patternAsRegex -and |
| 44 | + $socketConnection.WebSocketContext.RequestUri -match $pattern |
| 45 | + ) { |
| 46 | + $socketConnection.WebSocket |
| 47 | + } |
| 48 | + elseif ( |
| 49 | + $pattern -and |
| 50 | + $socketConnection.WebSocketContext.RequestUri -like $pattern |
| 51 | + ) { |
| 52 | + $socketConnection.WebSocket |
| 53 | + } |
| 54 | + else { |
| 55 | + $socketConnection.WebSocket |
| 56 | + } |
| 57 | + } |
| 58 | +) |
| 59 | + |
| 60 | + |
| 61 | +if ($message -is [Collections.IList] -and $message -isnot [byte[]]) { |
| 62 | + $Message | sendMessage -Sockets $socketList |
| 63 | +} else { |
| 64 | + sendMessage -msg $Message -Sockets $socketList |
| 65 | +} |
| 66 | + |
| 67 | + |
| 68 | + |
| 69 | + |
0 commit comments