PowerShell TCP 服务器 [英] PowerShell TCP Server

查看:92
本文介绍了PowerShell TCP 服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

$endpoint = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Any, 8989)$listener = 新对象 System.Net.Sockets.TcpListener $endpoint$listener.Start()做 {$client = $listener.AcceptTcpClient() # 会阻塞这里直到连接$stream = $client.GetStream();$reader = 新对象 System.IO.StreamReader $stream做 {$line = $reader.ReadLine()写主机 $line -fore 青色} while ($line -and $line -n​​e ([char]4))$reader.Dispose()$stream.Dispose()$client.Dispose()} while ($line -n​​e ([char]4))$listener.Stop()

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

解决方案

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

$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 = 新对象 Timers.Timer$Timer.Enabled = $true$Timer.Interval = 1000Register-ObjectEvent -SourceIdentifier MonitorClientConnection -InputObject $Timer -EventName Elapsed -Action {虽然($CnQueue.count -ne 0){$client = $CnQueue.Dequeue()$newRunspace = [RunSpaceFactory]::CreateRunspace()$newRunspace.Open()$newRunspace.SessionStateProxy.setVariable("client", $client)$newPowerShell = [PowerShell]::Create()$newPowerShell.Runspace = $newRunspace$进程= {$stream = $client.GetStream();$reader = 新对象 System.IO.StreamReader $stream[控制台]::WriteLine("内部处理")# 你在这里有客户,所以在这里做任何你想做的事.# 这是一个单独的线程,所以如果你在这里编写阻塞代码,它不会影响程序的任何其他部分}$jobHandle = $newPowerShell.AddScript($process).BeginInvoke()#jobHandle 你需要保存以备将来清理}}$监听器 = {$Listener['listener'] = New-Object System.Net.Sockets.TcpListener("127.0.0.1", "1234")$Listener['listener'].Start()[控制台]::WriteLine("收听:1234")而 ($true) {$c = $Listener['listener'].AcceptTcpClient()如果($c -ne $Null){[控制台]::WriteLine("{0} >> Accepted Client " -f (Get - Date).ToString())$CnQueue.Enqueue($c)}别的 {[控制台]::WriteLine("正在关闭")休息}}}$Timer.Start()$Global:handle = $newPowerShell.AddScript($listener).BeginInvoke()

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

I would like to ask you, how it is possible to handle multiple connection threads.

I have implemented TCP server in the following way:

$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()

This code can handle just one thread in time. Can you give me an advice on how to create a TCP server in PowerShell that can handle multiple clients?

解决方案

For handling multiple clients you need multiple threads and for that you need to use runspaces. Below is the working code which accepts multiple clients and do the processing of each client in separate thread (runspace)

$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()

For more detailed example please go here

这篇关于PowerShell TCP 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆