Skip to content

Instantly share code, notes, and snippets.

@Molochnikov
Created November 19, 2020 18:18
Show Gist options
  • Select an option

  • Save Molochnikov/c61fb099029a16a3cc2bb394889bcee1 to your computer and use it in GitHub Desktop.

Select an option

Save Molochnikov/c61fb099029a16a3cc2bb394889bcee1 to your computer and use it in GitHub Desktop.
TCP/HTTP Server on PowerShell
$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
$Job = 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.HttpListener #System.Net.Sockets.TcpListener("127.0.0.1", "123")
$Listener['listener'].Prefixes.Add("http://*:8080/")
$Listener['listener'].Start()
[console]::WriteLine("Listening...")
for (;;) {
$c = $Listener['listener'].GetContext() #.AcceptTcpClient()
[console]::WriteLine($c)
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment