如果你不打算跟客戶做任何事情,那麼你就必須接受他們,只需停止監聽:
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()
}
在http://msdn.microsoft.com/en-us/library/zsyxy9k2.aspx,你有''BeginAcceptTcpClient''和''EndAcceptTcpClient''功能做異步接受,但你需要設置回調。在兩者之間插入啓動 - 睡眠5並完成。 –