如何使用PowerShell V2使用Websocket客户端打开与URL的长期连接? [英] How to use a Websocket client to open a long-lived connection to a URL, using PowerShell V2?
问题描述
我正在尝试使用PowerShell V2(出于测试目的)使用Slack初始化实时消息(rtm)实例.但是根据Slack的常见问题解答,要连接到他们的rtm API,我需要通过Websocket客户端使用wss://协议来流式传输相关事件.我还试图使其成为异步连接(接收和连接).
I am trying to use PowerShell V2 (testing purposes) to initiate a real-time messaging (rtm) instance with Slack. But according to Slack's FAQ, to connect to their rtm API, I need to use the wss:// protocol via a Websocket client to stream events associated. I am also trying to make it an asynchronous connection (receiving as well as connecting).
这不起作用:
$webSock = New-Object System.Net.WebSocket.ClientWebSocket
$client = New-Object System.Threading.CancellationToken
另一件事是,我需要一个在PowerShell V2中从JSON转换的函数.
One other thing is that I need a function to convert from JSON in PowerShell V2.
我尝试使用它,但是也无法正常工作
I tried using this but it doesn't work too:
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)
}
推荐答案
可以使用.NET的 System.Net.WebSockets.ClientWebSocket
类进行此操作.要使用该类,您需要运行Windows 8或Server 2012或更高版本作为基础操作系统,因此,我认为您至少要拥有PowerShell v3(因此, ConvertFrom-Json
cmdlet).您还需要使用 System.ArraySegment
.NET类.
It is possible to use .NET's System.Net.WebSockets.ClientWebSocket
class to do this. You need to be running Windows 8 or Server 2012 or newer as your underlying OS to utilise this class, so therefore I think you'd have at least PowerShell v3 regardless (and as a result the ConvertFrom-Json
cmdlet). You also need to make use of the System.ArraySegment
.NET class.
我创建了一个简单的框架,该框架演示了如何使用各种类与PowerShell脚本中的Slack RTM API进行交互.您可以在GitHub上找到该项目: https://github.com/markwragg/Powershell-SlackBot
I've created a simple framework that demonstrates how to use the various classes to interact with the Slack RTM API from a PowerShell script. You can find the project on GitHub here: https://github.com/markwragg/Powershell-SlackBot
I've also blogged about it in more detail here: http://wragg.io/powershell-slack-bot-using-the-real-time-messaging-api/
这篇关于如何使用PowerShell V2使用Websocket客户端打开与URL的长期连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!