如何使用Websocket客户端打开到URL的长期连接,使用PowerShell V2



我正在尝试使用PowerShell V2(测试目的)与Slack启动实时消息传递(rtm)实例。但是根据Slack的FAQ,要连接到他们的rtm API,我需要通过Websocket客户端使用wss://协议来传输相关的事件。我还试图使其成为异步连接(接收以及连接)。

这行不通:

$webSock = New-Object System.Net.WebSocket.ClientWebSocket
$client = New-Object System.Threading.CancellationToken

另一件事是,我需要一个函数从JSON转换在PowerShell V2。

我试着使用这个,但它不工作了:

function ConvertFrom-Json20([object] $item){ 
    add-type -assembly system.web.extensions
    $ps_js=new-object system.web.script.serialization.javascriptSerializer
    #The comma operator is the array construction operator in PowerShell
    return ,$ps_js.DeserializeObject($item)
}

奇怪的是,我最近也有同样的需求。感谢Mark Wragg和他提供的有用链接,这里有一些快速的代码。你至少需要Windows 8和Server 2012来实现这些功能。

Try{  
    Do{
        $URL = 'ws://YOUR_URL_HERE/API/WebSocketHandler.ashx'
        $WS = New-Object System.Net.WebSockets.ClientWebSocket                                                
        $CT = New-Object System.Threading.CancellationToken
        $WS.Options.UseDefaultCredentials = $true
        #Get connected
        $Conn = $WS.ConnectAsync($URL, $CT)
        While (!$Conn.IsCompleted) { 
            Start-Sleep -Milliseconds 100 
        }
        Write-Host "Connected to $($URL)"
        $Size = 1024
        $Array = [byte[]] @(,0) * $Size
        #Send Starting Request
        $Command = [System.Text.Encoding]::UTF8.GetBytes("ACTION=Command")
        $Send = New-Object System.ArraySegment[byte] -ArgumentList @(,$Command)            
        $Conn = $WS.SendAsync($Send, [System.Net.WebSockets.WebSocketMessageType]::Text, $true, $CT)
        While (!$Conn.IsCompleted) { 
            #Write-Host "Sleeping for 100 ms"
            Start-Sleep -Milliseconds 100 
        }
        Write-Host "Finished Sending Request"
        #Start reading the received items
        While ($WS.State -eq 'Open') {                        
            $Recv = New-Object System.ArraySegment[byte] -ArgumentList @(,$Array)
            $Conn = $WS.ReceiveAsync($Recv, $CT)
            While (!$Conn.IsCompleted) { 
                    #Write-Host "Sleeping for 100 ms"
                    Start-Sleep -Milliseconds 100 
            }
            #Write-Host "Finished Receiving Request"
            Write-Host [System.Text.Encoding]::utf8.GetString($Recv.array)

        }   
    } Until ($WS.State -ne 'Open')
}Finally{
    If ($WS) { 
        Write-Host "Closing websocket"
        $WS.Dispose()
    }
}

可以使用。net的System.Net.WebSockets.ClientWebSocket类来完成此操作。你需要运行Windows 8或Server 2012或更新作为你的底层操作系统来利用这个类,所以我认为你至少有PowerShell v3不管(结果是ConvertFrom-Json cmdlet)。您还需要使用System.ArraySegment . net类。

我创建了一个简单的框架,演示了如何使用各种类从PowerShell脚本与Slack RTM API进行交互。你可以在GitHub上找到这个项目:https://github.com/markwragg/Powershell-SlackBot

我也在博客上详细介绍过:http://wragg.io/powershell-slack-bot-using-the-real-time-messaging-api/

相关内容

  • 没有找到相关文章

最新更新