Powershell AcceptTcpClient() 不能被 Ctrl-C 中断

标签 powershell tcp client control-c

我正在使用 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/

相关文章:

powershell - splatting 时使用哈希表作为参数?

Powershell 匹配行列表中的精确字符串

c++ - 如何从多个 IP 数据包重建 TCP 流?

javascript - NodeJS 中 requestAnimationFrame() 的服务器端实现

php - 如何使用 PHP 获取客户端的 IP 地址和端口?

powershell - 在 PowerShell 中运行函数

从 Invoke-WebRequest 的响应中解析 XML

sockets - 通过浏览器呈现网页

tcp - TCP 窗口缩放选项的动态设置

java - 无法附加到 HDFS