2012-10-29 135 views
2

我目前有一個腳本在指定的端口上偵聽。我希望此腳本在5秒後停止運行,無論連接與否。有沒有辦法可以做到這一點?某種延遲在powershell中「x」秒後停止函數

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 
+0

在http://msdn.microsoft.com/en-us/library/zsyxy9k2.aspx,你有''BeginAcceptTcpClient''和''EndAcceptTcpClient''功能做異步接受,但你需要設置回調。在兩者之間插入啓動 - 睡眠5並完成。 –

回答

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