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()
}

另一种选择是在侦听器上使用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 回答