クライアントに対して何もするつもりがない場合は、それらを受け入れる必要はなく、ただ聞くのをやめることができます。
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メソッド(BeginAcceptTcpClient、EndAcceptTcpClient )を利用できます。
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()
}