PowerShell TCP Server

筅森魡賤 提交于 2019-12-04 09:00:37

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!