Skip to content

Instantly share code, notes, and snippets.

@jdgregson
Created January 2, 2020 19:04
Show Gist options
  • Save jdgregson/4a9aa8a57afa7bf41667e57ba60898e2 to your computer and use it in GitHub Desktop.
Save jdgregson/4a9aa8a57afa7bf41667e57ba60898e2 to your computer and use it in GitHub Desktop.
Simple example of listening on a port and reading from a socket in PowerShell.
$listener = [System.Net.Sockets.TcpListener]9999
$listener.Start()
while ($true) {
$client = $listener.AcceptTcpClient()
$rEndpoint = $client.client.RemoteEndPoint
$data = ""
$stream = $client.GetStream()
$buffer = New-Object System.Byte[] 1024
while ($client.Connected -and $stream.DataAvailable -and
($i = $stream.Read($buffer, 0, $buffer.Length)) -ne 0) {
$EncodedText = New-Object System.Text.ASCIIEncoding
$data += $EncodedText.GetString($buffer, 0, $i)
}
Write-Host "$rEndpoint`: $data"
$stream.Close()
$client.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment