gpt4 book ai didi

PowerShell TCP 服务器

转载 作者:可可西里 更新时间:2023-11-01 02:32:57 26 4
gpt4 key购买 nike

我想问你,如何处理多个连接线程。

我已经通过以下方式实现了 TCP 服务器:

$endpoint = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Any, 8989)
$listener = New-Object System.Net.Sockets.TcpListener $endpoint
$listener.Start()

do {
$client = $listener.AcceptTcpClient() # will block here until connection
$stream = $client.GetStream();
$reader = New-Object System.IO.StreamReader $stream
do {
$line = $reader.ReadLine()
Write-Host $line -fore cyan
} while ($line -and $line -ne ([char]4))

$reader.Dispose()
$stream.Dispose()
$client.Dispose()
} while ($line -ne ([char]4))
$listener.Stop()

这段代码只能及时处理一个线程。关于如何在 PowerShell 中创建可以处理多个客户端的 TCP 服务器,您能给我一些建议吗?

最佳答案

要处理多个客户端,您需要多个线程,为此您需要使用 runspaces 。下面是接受多个客户端并在单独的线程(运行空间)中处理每个客户端的工作代码

$Global:Listener = [HashTable]::Synchronized(@{})
$Global:CnQueue = [System.Collections.Queue]::Synchronized((New-Object System.collections.queue))
$Global:space = [RunSpaceFactory]::CreateRunspace()
$space.Open()
$space.SessionStateProxy.setVariable("CnQueue", $CnQueue)
$space.SessionStateProxy.setVariable("Listener", $Listener)
$Global:newPowerShell = [PowerShell]::Create()
$newPowerShell.Runspace = $space
$Timer = New-Object Timers.Timer
$Timer.Enabled = $true
$Timer.Interval = 1000
Register-ObjectEvent -SourceIdentifier MonitorClientConnection -InputObject $Timer -EventName Elapsed -Action {
While($CnQueue.count -ne 0) {
$client = $CnQueue.Dequeue()
$newRunspace = [RunSpaceFactory]::CreateRunspace()
$newRunspace.Open()
$newRunspace.SessionStateProxy.setVariable("client", $client)
$newPowerShell = [PowerShell]::Create()
$newPowerShell.Runspace = $newRunspace
$process = {
$stream = $client.GetStream();
$reader = New-Object System.IO.StreamReader $stream
[console]::WriteLine("Inside Processing")
# You have client here so do whatever you want to do here.
# This is a separate thread so if you write blocking code here, it will not impact any other part of the program
}
$jobHandle = $newPowerShell.AddScript($process).BeginInvoke()
#jobHandle you need to save for future to cleanup
}
}
$listener = {
$Listener['listener'] = New-Object System.Net.Sockets.TcpListener("127.0.0.1", "1234")
$Listener['listener'].Start()
[console]::WriteLine("Listening on :1234")
while ($true) {
$c = $Listener['listener'].AcceptTcpClient()
If($c -ne $Null) {
[console]::WriteLine("{0} >> Accepted Client " -f (Get - Date).ToString())
$CnQueue.Enqueue($c)
}
Else {
[console]::WriteLine("Shutting down")
Break
}
}
}
$Timer.Start()
$Global:handle = $newPowerShell.AddScript($listener).BeginInvoke()

有关更详细的示例,请转到 here

关于PowerShell TCP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44518636/

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