繁体   English   中英

Powershell WebSocket(ClientWebSocket) 发送消息

[英]Powershell WebSocket(ClientWebSocket) send message

环境:MacOs

我正在尝试使用System.Net.HttpListener创建菜单。

有什么方法可以使用[System.Net.WebSockets.ClientWebSocket]$WebSocket向使用 Powershell 的浏览器客户端发送信息?

您可以这样做,但为了让 web 服务器向浏览器发送任何信息,浏览器必须发起请求,最常见的情况是 JavaScript。

首先,为服务器设置 HTTP 监听器。

#Setting up the listener
$Server = [System.Net.HttpListener]::new()
$Server.Prefixes.Add('http://localhost:8001/')
$Server.Start()

这将启动 web 服务器侦听指定入口点上的请求。 接下来,我们定义一个简短的帮助器 function,此脚本将使用它来封装将响应发送回浏览器。

Function Send-WebServerResponse($InputObject){
    $JSON = $InputObject | ConvertTo-Json
    $buffer = [System.Text.Encoding]::UTF8.GetBytes($JSON)
    $Context.Response.ContentLength64 = $buffer.Length
    $Context.Response.OutputStream.Write($buffer, 0, $buffer.length)
    $Context.Response.OutputStream.Close()
    }

如果这是一个 MVC 应用程序,下一步是编写 Controller 逻辑。 基本上是路由层,所以脚本知道如何根据请求的类型做出响应。

#Listening for a particular header value
$Context = $Server.GetContext()

    Write-Host "$($Context.Request.UserHostAddress) [$($Context.Request.HttpMethod)]=> $($Context.Request.Url)"  -ForegroundColor Green    

$RequestData = $Context.Request.Headers.GetValues('RequestData')
    if ($Context.Request.Url.AbsolutePath -eq '/TestMe'){
        Write-Host "Received request for /TestMe endpoint..."  -ForegroundColor Green
        $Body = [System.IO.StreamReader]::new($Context.Request.InputStream, $Context.Request.ContentEncoding)
        $Data = $Body.ReadToEnd() | convertfrom-stringdata
        $Body.Close()
        Send-WebServerResponse "Request Received successfully to /TestMe"

    }

最后,这是 JS 从这个监听器请求信息的样子:

$.ajax({
            //the url to send the data to
            url: "TestMe",
            //the data to send to
            data: {SomeParam : "SomeValue"},
            //type. for eg: GET, POST
            type: "POST",
            //datatype expected to get in reply form server
            dataType: "json",
            //on success
            success: function(data){
                if (data){
                    Console.Log("Request Success");
                }
                else{
                    Console.Log("Request Failed!");
                }


            },
            //on error
            error: function(){
                //bad request

            }
        });

在@ScottCorio 的帮助下写了这个答案,他教了我这个方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM