# 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: 6355
# x-derived-from-id: 6759
# x-archived: 2017-04-01T02:43:09
# x-published: 2017-05-24T13:51: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()
}
