How to Send & receive Websocket client Requests, responses in JSON format in PowerShell

Viewed 729

With the below PowerShell commands, I am able to open the connection using Websocket.

$mySock = New-Object System.Net.WebSockets.ClientWebSocket
$CT = New-Object System.Threading.CancellationToken($false)
$CTS = New-Object System.Threading.CancellationTokenSource
$mySock.Options.UseDefaultCredentials = $true
$connectTask  = $mySock.ConnectAsync($URL, $CTS.Token)

The result as below:

PS C:\PS1> $mySock
Options                : System.Net.WebSockets.ClientWebSocketOptions
CloseStatus            : 
CloseStatusDescription : 
SubProtocol            : 
State                  : Open
PS C:\PS1>

My question is how do I send a request JSON format & also expect to receive the response in JSON format? Any help/guide would be much appreciated.

The document states as below: LOGIN Request When WebSocket connection is opened, the first command to the Streamer Server must be a LOGIN command with the following parameters.

Sample login request:

{
"service": "ADMIN",
"requestid": "1",
"command": "LOGIN", 
"account": "your_account", 
"source": "your_source_id", 
"parameters": {
              "token": "027363a5a5acd5", 
              "version": "1.0", 
              "credential": "userid%3DMYUSER20%26token%abcd"
              }
}

Sample login successful response:

{
"response": [
{
"service": "ADMIN", 
"requestid": "1", 
"command": "LOGIN", 
"timestamp": 1400607506478, 
"content": {
           "code": 0, 
           "msg": "02-1"
           }
        }
    ]
}
1 Answers

Not sure if you figured it out yet or not. How I did it was to convert the logon request to JSON and encode it in UTF8 and put it into an 1024 bit array segment using example code I found. Then I send it asynchronously back to the target.

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

When you receieve the response it must also be an array segement data type.

$Recv = New-Object System.ArraySegment[byte] -ArgumentList @(,$Array)
$Conn = $WS.ReceiveAsync($Recv, $CT)

This line will then get the return

[System.Text.Encoding]::utf8.GetString($Recv.array)

To keep getting all future messages I then created a Do until loop that continues to run until the web socket is no longer open.

Related