2

現在、指定されたポートでリッスンするスクリプトがあります。接続されているかどうかに関係なく、このスクリプトの実行を5秒後に停止したいと思います。私がそれを行うことができる方法はありますか?ある種の遅延

function listen-port ($port) {
    $endpoint = new-object System.Net.IPEndPoint ([ipaddress]::any,$port)
    $listener = new-object System.Net.Sockets.TcpListener $endpoint
    $listener.start()
    $listener.AcceptTcpClient() # will block here until connection
    $listener.stop()
    }
listen-port 25
4

1 に答える 1

2

クライアントに対して何もするつもりがない場合は、それらを受け入れる必要はなく、ただ聞くのをやめることができます。

function listen-port ($port) {
$endpoint = new-object System.Net.IPEndPoint ([ipaddress]::any,$port)
$listener = new-object System.Net.Sockets.TcpListener $endpoint
$listener.start()
Start-Sleep -s 5
$listener.stop()
}

クライアントで何かを行う必要がある場合は、非同期のAcceptTcpClientメソッド(BeginAcceptTcpClientEndAcceptTcpClient )を利用できます。

function listen-port ($port) {
$endpoint = new-object System.Net.IPEndPoint ([ipaddress]::any,$port)
$listener = new-object System.Net.Sockets.TcpListener $endpoint
$listener.start()
$ar = $listener.BeginAcceptTcpClient($null,$null) # will not block here until connection

if ($ar.AsyncWaitHandle.WaitOne([timespan]'0:0:5') -eq $false) 
{ 
 Write-Host "no connection within 5 seconds" 
}
else
{ 
 Write-Host "connection within 5 seconds"
 $client = $listener.EndAcceptTcpClient($ar)
}

$listener.stop()
}

もう1つのオプションは、リスナーでPendingメソッドを使用することです。

function listen-port ($port) {
$endpoint = new-object System.Net.IPEndPoint ([ipaddress]::any,$port)
$listener = new-object System.Net.Sockets.TcpListener $endpoint
$listener.start()
Start-Sleep -s 5

if ($listener.Pending() -eq $false)
{
 Write-Host "nobody connected"
} 
else
{ 
 Write-Host "somebody connected"
 $client = $listener.AcceptTcpClient()
}

$listener.stop()
}
于 2012-10-29T21:59:35.577 に答える