Skip to content

Instantly share code, notes, and snippets.

@carcigenicate
Created November 4, 2021 14:09
Show Gist options
  • Save carcigenicate/b8012807a93da3f6222dfc4cc9eebc33 to your computer and use it in GitHub Desktop.
Save carcigenicate/b8012807a93da3f6222dfc4cc9eebc33 to your computer and use it in GitHub Desktop.
using namespace System.Net.Sockets
$Encoder = [System.Text.Encoding]::UTF8
$SIZE_BUFFER_SIZE = 4
$PROMPT = ">>> "
function Read-NBytes {
Param($Stream, $NToRead)
$Buffer = [byte[]]::new($NToRead)
$NRead = 0
#Write-Host "Entering loop to read $NToRead bytes."
while ($NRead -lt $NToRead) {
$NRead += $Stream.Read($Buffer, $NRead, ($NToRead - $NRead))
#Write-Host "Read $NRead"
}
return $Buffer
}
function Start-HandlerLoop {
Param($ClientSock)
#Write-Host "Starting command loop..."
$Stream = $ClientSock.GetStream()
while ($true) {
Write-Host $PROMPT -NoNewline
$Command = Read-Host
$CommandBytes = $Encoder.GetBytes($Command)
if ($Command) {
# Send command length and then command
$NToSendBytes = [System.BitConverter]::GetBytes($Command.Length)
$Stream.Write($NToSendBytes, 0, $SIZE_BUFFER_SIZE)
$Stream.Write($CommandBytes, 0, $Command.Length)
if ($Command -iin @("quit", "exit")) {
break
} else {
# Recieve response length and response
$SizeBytes = Read-NBytes $Stream $SIZE_BUFFER_SIZE
$NToRead = [System.BitConverter]::ToInt32($SizeBytes, 0)
$ReadBytes = Read-NBytes $Stream $NToRead
if ($ReadBytes) {
Write-Host ($Encoder.GetString($ReadBytes))
}
}
}
}
}
function Wait-ForConnection {
Param($HostName, $Port)
$IPAddress = [System.Net.IPAddress]::Parse($HostName)
$Server = New-Object TcpListener($IPAddress, $Port)
$Server.Start() # TODO: Handle exceptions from bad addresses
$Client = $Server.AcceptTcpClient()
return $Server, $Client
}
if ($args.Length -eq 2) {
Write-Host "Starting handler and waiting for connection..."
$Server, $Client = Wait-ForConnection $args[0] ([Int32]$args[1])
try {
Start-HandlerLoop $Client
} finally {
$Client.Close()
$Server.Stop()
}
} else {
Write-Host "Two arguments are required. Pass the address and port number to bind to."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment