我正在使用 Powershell 编写一个简单的 TCP/IP 服务器。我注意到 Ctrl-C 不能中断 AcceptTcpClient() 调用。 Ctrl-C 在通话后工作正常。我四处搜索,到目前为止还没有人报告过类似的问题。
可以通过以下简单代码重复该问题。我使用的是 Windows 10,最新补丁,带有 native Powershell 终端,而不是 Powershell ISE。
$listener=new-object System.Net.Sockets.TcpListener([system.net.ipaddress]::any, 4444)
$listener.start()
write-host "listener started at port 4444"
$tcpConnection = $listener.AcceptTcpClient()
write-host "accepted a client"
这是我运行时发生的事情
ps1> .\test_ctrl_c.ps1
listener started at port 4444
(Ctrl-C doesn't work here)
最佳答案
在得到@mklement0 的回答后,我放弃了我原来的干净代码。我想出了一个解决方法。现在 Ctrl-C 可以中断我的程序
$listener=new-object System.Net.Sockets.TcpListener([system.net.ipaddress]::any, 4444)
$listener.start()
write-host "listener started at port 4444"
while ($true) {
if ($listener.Pending()) {
$tcpConnection = $listener.AcceptTcpClient()
break;
}
start-sleep -Milliseconds 1000
}
write-host "accepted a client"
现在可以使用 Ctrl-C
ps1> .\test_ctrl_c.ps1
listener started at port 4444
(Ctrl-C works here)
关于Powershell AcceptTcpClient() 不能被 Ctrl-C 中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60896213/