Send JSON via websocket connection in PowerShell

Viewed 117

Here is some code I cobbled together based on various SO questions. It connects to the socket server (nodejs) and sends something, but it's not right.

$ws = New-Object Net.WebSockets.ClientWebSocket
$cts = New-Object Threading.CancellationTokenSource
$ct = New-Object Threading.CancellationToken($false)
print "Connecting..."

$connectTask = $ws.ConnectAsync("ws://127.0.0.1:8081/", $cts.Token)
do { Sleep(1) }
until ($connectTask.IsCompleted)
print "Connected!"
$msg = {type: "status", message: "starting"}

$Array = [byte[]] @(,0) * 1024
$Command = [System.Text.Encoding]::UTF8.GetBytes($msg)
$Send = New-Object System.ArraySegment[byte] -ArgumentList @(,$Command)
$Conn = $WS.SendAsync($Send, [System.Net.WebSockets.WebSocketMessageType]::Text, $True, $CT)

$closetask = $ws.CloseAsync(
    [System.Net.WebSockets.WebSocketCloseStatus]::Empty,
    "",
    $ct
)
$ws.Dispose()

The socket server receives a "buffer":

enter image description here

How can I send JSON?

1 Answers

Make a couple tweaks to your $msg object and then you can just convert the message to JSON using ConvertTo-Json.

$msg = @{type = "status"; message = "starting"}
$Send = $msg | ConvertTo-Json -Depth 10
Related