PoshCode Archive  Artifact Content

Artifact 0f4888c70cb60f19a3af7ad0620249720fabf5f009526c6f90ccee40f64b8cc0:

  • File TCP-Client-Server.ps1 — part of check-in [494892dc2e] at 2018-06-10 14:20:32 on branch trunk — An example of a client/server that works in PowerShell (user: rtsssdada size: 1373)

# 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: rtsssdada
# license: CC0
# function: listen-port
# x-poshcode-id: 6759
# x-archived: 2017-03-31T03:10:23
# x-published: 2017-02-27T21:31: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.Close()
    $stream.Dispose()
    $client.Close()
}