PoshCode Logo PowerShell Code Repository

TCP Client/Server by powershellshock 8 weeks ago (modification of post by rtsssdada view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/6759"></script>download | new post

An example of a client/server that works in PowerShell

  1. function listen-port ($port=8989) {
  2.     $endpoint = new-object System.Net.IPEndPoint ([system.net.ipaddress]::any, $port)
  3.     $listener = new-object System.Net.Sockets.TcpListener $endpoint
  4.     $listener.start()
  5.  
  6.     do {
  7.         $client = $listener.AcceptTcpClient() # will block here until connection
  8.         $stream = $client.GetStream();
  9.         $reader = New-Object System.IO.StreamReader $stream
  10.         do {
  11.  
  12.             $line = $reader.ReadLine()
  13.             write-host $line -fore cyan
  14.         } while ($line -and $line -ne ([char]4))
  15.         $reader.Dispose()
  16.         $stream.Dispose()
  17.         $client.Dispose()
  18.     } while ($line -ne ([char]4))
  19.     $listener.stop()
  20. }
  21.  
  22.  
  23.  
  24. function send-msg ($message=$([char]4), $port=8989, $server="localhost") {
  25.     $client = New-Object System.Net.Sockets.TcpClient $server, $port
  26.     $stream = $client.GetStream()
  27.     $writer = New-Object System.IO.StreamWriter $stream
  28.     $writer.Write($message)
  29.     $writer.Close()
  30.     $stream.Dispose()
  31.     $client.Close()
  32. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me