我当前有一个监听指定端口的脚本。我希望这个脚本在 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
最佳答案
如果您不打算对客户做任何事情,那么您不必接受他们并且可以停止倾听:
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()
}
另一个选择是使用 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()
}
关于function - powershell 中 "x"秒后停止函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13129952/