Skip to content

Commit

Permalink
#895: fixes for text encoding, and adhoc connecting
Browse files Browse the repository at this point in the history
  • Loading branch information
Badgerati committed Apr 29, 2022
1 parent a0d6b5d commit 5a9ecc5
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 30 deletions.
29 changes: 9 additions & 20 deletions examples/web-signal-connection.ps1
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
param($token)

$path = Split-Path -Parent -Path (Split-Path -Parent -Path $MyInvocation.MyCommand.Path)
Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop

# or just:
# Import-Module Pode

# create a server, and start listening
Start-PodeServer {
Start-PodeServer -EnablePool WebSockets {

# listen
Add-PodeEndpoint -Address * -Port 8092 -Protocol Http
Expand All @@ -23,26 +21,17 @@ Start-PodeServer {
# }
# }

$slack = Invoke-RestMethod -Method Post -Uri 'https://slack.com/api/apps.connections.open' -Headers @{ Authorization = "Bearer $token" }
Connect-PodeWebSocket -Name 'Slack' -Url $slack.url -ScriptBlock {
# $WsEvent.Request.Body | out-default

$msg = $WsEvent.Request.Body | ConvertFrom-Json -AsHashtable
$msg | out-default
switch ($msg.type) {
'disconnect' {
Disconnect-PodeWebSocket
}

'events_api' {
Send-PodeWebSocket -Message (@{
envelope_id = $msg.envelope_id
} | ConvertTo-Json -Compress) # acknowledge

}
Add-PodeRoute -Method Get -Path '/connect' -ScriptBlock {
Connect-PodeWebSocket -Name 'Test' -Url 'wss://ws.ifelse.io/' -ScriptBlock {
$WsEvent.Request | out-default
}
}

Add-PodeTimer -Name 'Test' -Interval 10 -ScriptBlock {
$rand = Get-Random -Minimum 10 -Maximum 1000
Send-PodeWebSocket -Name 'Test' -Message "hello $rand"
}

# Add-PodeRoute -Method Get -Path '/reset' -ScriptBlock {
# Reset-PodeWebSocket -Name 'Example'
# }
Expand Down
2 changes: 1 addition & 1 deletion src/Listener/PodeReceiver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public void ConnectWebSocket(string name, string url)

public PodeWebSocket GetWebSocket(string name)
{
return WebSockets[name];
return (WebSockets.ContainsKey(name) ? WebSockets[name] : default(PodeWebSocket));
}

public void DisconnectWebSocket(string name)
Expand Down
4 changes: 2 additions & 2 deletions src/Listener/PodeWebSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,14 +104,14 @@ public async void Receive()
}
}

public void Send(string message)
public void Send(string message, WebSocketMessageType type = WebSocketMessageType.Text)
{
if (WebSocket.State != WebSocketState.Open)
{
return;
}

WebSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(message)), WebSocketMessageType.Binary, true, Receiver.CancellationToken).Wait();
WebSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(message)), type, true, Receiver.CancellationToken).Wait();
}

public void Disconnect()
Expand Down
2 changes: 2 additions & 0 deletions src/Private/Context.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,8 @@ function New-PodeRunspacePools
Pool = [runspacefactory]::CreateRunspacePool(1, $PodeContext.Threads.WebSockets + 1, $PodeContext.RunspaceState, $Host)
State = 'Waiting'
}

New-PodeWebSocketReceiver
}

# setup schedule runspace pool -if we have any schedules
Expand Down
48 changes: 41 additions & 7 deletions src/Public/WebSockets.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,19 @@ function Connect-PodeWebSocket
# ensure we have a receiver
New-PodeWebSocketReceiver

# fail if already exists
if (Test-PodeWebSocket -Name $Name) {
throw "Already connected to websocket with name '$($Name)'"
}

# connect
$PodeContext.Server.WebSockets.Receiver.ConnectWebSocket($Name, $Url)
try {
$PodeContext.Server.WebSockets.Receiver.ConnectWebSocket($Name, $Url)
}
catch {
throw "Failed to connect to websocket: $($_.Exception.Message)"
}

$PodeContext.Server.WebSockets.Connections[$Name] = @{
Name = $Name
Url = $Url
Expand Down Expand Up @@ -84,8 +95,10 @@ function Disconnect-PodeWebSocket
throw "No Name for a WebSocket to disconnect from supplied"
}

$PodeContext.Server.WebSockets.Receiver.DisconnectWebSocket($Name)
$PodeContext.Server.WebSockets.Connections.Remove($Name)
if (Test-PodeWebSocket -Name $Name) {
$PodeContext.Server.WebSockets.Receiver.DisconnectWebSocket($Name)
$PodeContext.Server.WebSockets.Connections.Remove($Name)
}
}

function Send-PodeWebSocket
Expand All @@ -98,19 +111,26 @@ function Send-PodeWebSocket

[Parameter()]
[string]
$Message
$Message,

[Parameter()]
[ValidateSet('Text', 'Binary')]
[string]
$Type = 'Text'
)

if ([string]::IsNullOrWhiteSpace($Name) -and ($null -ne $WsEvent)) {
$WsEvent.Request.WebSocket.Send($Message)
$WsEvent.Request.WebSocket.Send($Message, $Type)
return
}

if ([string]::IsNullOrWhiteSpace($Name)) {
throw "No Name for a WebSocket to send message to supplied"
}

$PodeContext.Server.WebSockets.Receiver.GetWebSocket($Name).Send($Message)
if (Test-PodeWebSocket -Name $Name) {
$ws.Send($Message, $Type)
}
}

function Reset-PodeWebSocket
Expand All @@ -135,5 +155,19 @@ function Reset-PodeWebSocket
throw "No Name for a WebSocket to reset supplied"
}

$PodeContext.Server.WebSockets.Receiver.GetWebSocket($Name).Reconnect($Url)
if (Test-PodeWebSocket -Name $Name) {
$ws.Reconnect($Url)
}
}

function Test-PodeWebSocket
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]
$Name
)

return ($null -ne $PodeContext.Server.WebSockets.Receiver.GetWebSocket($Name))
}

0 comments on commit 5a9ecc5

Please sign in to comment.