Powershell: Simple TCP Client and Server

Hi,

these are TCP client and server which can simply used for testing if a specific TCP port is open

This is the server side. It listens at port 4444

# Server
$iPort = 4444
$TCPListener = New-Object System.Net.Sockets.TcpListener($iPort)
$TCPListener.Start();
[byte[]]$ReadBytesBuffer = New-Object byte[] 65536
# Here the code waits for an incoming connection
$TCPServer = $TCPListener.AcceptTcpClient();
write-host ("Connected from {0}" -f $TCPServer.Client.RemoteEndPoint.ToString())
$TCPServerDataStream = $TCPServer.GetStream()
do
{
    try
    {
       $iBytesRead= $TCPServerDataStream.read($ReadBytesBuffer , 0, $ReadBytesBuffer.Length)
       $TCPServerDataStream.Write([System.Text.Encoding]::Ascii.GetBytes('OK'),0,2)
       write-host ([text.encoding]::ASCII.GetString($ReadBytesBuffer ,0,$iBytesRead))
    }
    catch 
    {
       write-host ("Cannot read data from stream. Error: {0}" -f $_.Exception.Message)
    }
}
while($TCPServer.Connected)
write-host "Connection closed"
$TCPServerDataStream.Close()
$TCPServerDataStream.Dispose()
$TCPServer.Close()
$TCPServer.Dispose()
$TCPListener.Stop()

And the client side

[Net.Sockets.TCPClient]$TCPClient=New-Object System.Net.IPEndpoint ([ipaddress]::any,0)
$TCPClient.Connect("localhost",4444) 
$TCPClientDataStream = $TCPClient.GetStream()

Then you can send data multiple times from the client over the connection

$Data = [System.Text.Encoding]::Ascii.GetBytes('Message to TCP Server')    
$TCPClientDataStream.Write($Data,0,$Data.length)

Then close the connection

$TCPClient.Close()

Michael