gpt4 book ai didi

function - 在Powershell中的 “x”秒后停止功能

转载 作者:行者123 更新时间:2023-12-02 23:47:43 25 4
gpt4 key购买 nike

我目前有一个在指定端口上侦听的脚本。我希望此脚本在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方法( 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()
}

关于function - 在Powershell中的 “x”秒后停止功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13129952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com