Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Can't write to stream inside event

$
0
0

I am can try to run NHTTP(simple asynchronous HTTP server written in C# for the .NET framework. You can download this dll in nuget, or view source code on github) But i am cant write my own response to client from my server, because i am can't write to OutputStream.

My powershell script:

 


    Add-Type -Path "NHttp.dll"
   
    $server = New-Object NHttp.HttpServer
    $server.EndPoint =  new-object System.Net.IPEndPoint ([System.Net.IPAddress]::Parse("127.0.0.1"), 8080)
   
   
    $RequestReceived = {
       
        $request = $EventArgs.Request
        $response = $EventArgs.Response
   
        $global:response = $response.OutputStream.CanWrite
       
        $writer = New-Object System.IO.StreamWriter($response.OutputStream)
        $writer.AutoFlush = $true
        $writer.WriteLine("Hello World")   
       
       
    }
   
    Register-ObjectEvent -InputObject $server -EventName RequestReceived -SourceIdentifier RequestReceived -Action $RequestReceived
   
    $server.Start()
 

Always when my server receive request from client $global:response=False

And i have error in Job that run $RequestReceived Action:
New-Object: Exception calling ".ctor" with "1" argument: "The flow was not available
for the record."

And server response clean white page and StatusCode 200 to client.

But example for C# work perfectly:
 

    using (var server = new HttpServer())
    {
        server.RequestReceived += (s, e) =>
        {
            using (var writer = new StreamWriter(e.Response.OutputStream))
            {
                writer.Write("Hello world!");
            }
        };
   
        server.Start();
   
        Process.Start(String.Format("http://{0}/", server.EndPoint));
   
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }
 

Such behavior within the Action block when called Event created by Register-ObjectEvent occurs to me is not the first time. I try to solve it, changing "apartment" model(STA and MTA), but it not solve the problem. If you need i am have more examples.

Viewing all articles
Browse latest Browse all 6937

Trending Articles