PowerShell从管道中读取 - 不阻挡一方甚至双方?

时间:2014-06-10 12:38:40

标签: powershell named-pipes nonblocking

PowerShell脚本启动NamedPipe服务器:

$Enc = [System.Text.Encoding]::ASCII
$Buf = new-object byte[] 4096

$BaseName = "testpipe"
$n = 0;
do {
     $n++
     $pipeName = "$BaseName$n"
     $delPipe = [System.IO.Directory]::GetFiles("\\.\pipe\")|where{$_ -match $pipeName}
} while ( $delPipe.Length -gt 5 )

$pipeDir  = [System.IO.Pipes.PipeDirection]::InOut
$pipeMsg  = [System.IO.Pipes.PipeTransmissionMode]::Message
$pipeOpti = [System.IO.Pipes.PipeOptions]::Asynchronous
$pipe = New-Object system.IO.Pipes.NamedPipeServerStream( 
              $pipeName, $pipeDir, 1, $pipeMsg, $pipeOpti )
if ( !$pipe.IsConnected ) { $pipe.WaitForConnection() }
echo "Connected Pipe: $pipeName"
$pw = new-object System.IO.StreamWriter $pipe
$pw.AutoFlush = $true
$pr = new-object System.IO.StreamReader $pipe

PipeClient发送消息:

WriteLine(PipeHandel,"Hi Message"); FileFlush(PipeHandel);

现在我想从管道读取并找到两种方法1)客户端被阻止2)服务器被阻止?

1)这使得PipeClient挂起但PipeServer没有得到任何东西:(

function ReadMsg ($r, $e, $b) {
     try {
          $nTry=2
          $got = ""
          $Loops = 0
          do {
                # Read what data is available
                $foundmore = $false
                do {
                     try {
                          $read = $r.ReadAsync($b, 0, $b.Length)
                          if($read -gt 0) {
                                $foundmore = $true
                                $got += ($e.GetString($b, 0, $read))
                                $nTry = -1
                          }
                     } catch { $foundMore = $false; $read = 0; }
                } while($read -gt 0)
                if ($nTry -gt 0) {Start-Sleep -m 5; $nTry--;}
          } while($foundmore -or $nTry -gt 0)
     }
     finally { 
          return $got 
     }
}
ReadMsg pr $Enc $Buf

2)这让客户端发送消息但服务器等待客户端在服务器被阻塞的同时关闭管道?

function rdPipe ($r, $e, $b) {
     return $r.ReadToEnd()  # ReadLine()
}
rdPipe pr $Enc $Buf

双方是否有发送和接收异步消息的方式? 谢谢你的帮助, Gooly

1 个答案:

答案 0 :(得分:0)

上面的

$readTask<int>,而不是int。如果您确实要使用async,则应将以下if更改为:

if ($read.Result -gt 0) {
    ...
}