# encoding: ascii
# api: powershell
# title: TCP Client/Server
# description: An example of a client/server that works in PowerShell
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: listen-port
# x-poshcode-id: 4601
# x-archived: 2017-02-21T09:09:44
# x-published: 2014-11-11T18:16:00
#
#
function listen-port ($port=8989) {
$endpoint = new-object System.Net.IPEndPoint ([system.net.ipaddress]::any, $port)
$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()
}
function send-msg ($message=$([char]4), $port=8989, $server="localhost") {
$client = New-Object System.Net.Sockets.TcpClient $server, $port
$stream = $client.GetStream()
$writer = New-Object System.IO.StreamWriter $stream
$writer.Write($message)
$writer.Dispose()
$stream.Dispose()
$client.Dispose()
}