PoshCode Archive  Artifact [78c6ccf243]

Artifact 78c6ccf24337c2c92344f5708198490ab72b3db23ee744e7ad13645d94c882df:

  • File TCP-Client-Server.ps1 — part of check-in [3e0bfc339c] at 2018-06-10 13:43:35 on branch trunk — An example of a client/server that works in PowerShell (user: Joel Bennett size: 1382)

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