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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 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

1
2
3
[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

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

Then close the connection

1
$TCPClient.Close()

Michael