PoshCode Archive  Artifact Content

Artifact 93cb9d147325242747878af6ed461a29029d8804aeb5249bd2e6b48b1cbaf076:

  • File TCP-Client-Server.ps1 — part of check-in [8e2068f0d1] at 2018-06-10 14:13:52 on branch trunk — An example of a client/server that works in PowerShell (user: Joel Bennett size: 1407)

# 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()
}