Chapter6: Socket Programming

This section contain the following items:

  • 1.TCP server/client

1.TCP server/client

  • 1.TCP server

     Function Receive-TCPMessage { 
        param ( [ValidateNotNullOrEmpty()] 
        [int] $Port
    ) 
    try { 

    $endpoint = new-object System.Net.IPEndPoint([ipaddress]::any,$port) 
    $listener = new-object System.Net.Sockets.TcpListener $EndPoint
    $listener.start() 

    $data = $listener.AcceptTcpClient() # will block here until connection 
    $bytes = New-Object System.Byte[] 1024
    $stream = $data.GetStream() 

    while (($i = $stream.Read($bytes,0,$bytes.Length)) -ne 0){
        $EncodedText = New-Object System.Text.ASCIIEncoding
        $data = $EncodedText.GetString($bytes,0, $i)
        if($data.replace("`n"," ").replace("`r"," ") -eq  "kill  "){
            $ProcessActive = Get-Process uartecho -ErrorAction SilentlyContinue
            echo $ProcessActive
            if($ProcessActive -eq $null)
            {
                return 0
            }
            else
            {
                #do something
            }
        }else {
            return 0
        }

    }

    $stream.close()
    $listener.stop()
}catch [exception]{}
}
  • 2.TCP client

          Function Send-TCPMessage { 
              param ( [ValidateNotNullOrEmpty()] 
                  [string] $EndPoint, 
                  [int] $Port, 
                  $Message
              ) 
    
              $UTF8 = [System.Text.Encoding]::UTF8
              #$IP = [System.Net.Dns]::GetHostAddresses($EndPoint) 
              $Address = [System.Net.IPAddress]::Parse($IP) 
              $Socket = New-Object System.Net.Sockets.TCPClient($Address,$Port) 
              $data = $UTF8.GetBytes($Message)
              $Stream = $Socket.GetStream() 
              $Writer = New-Object System.IO.StreamWriter($Stream)
              $Message | %{
                  $Writer.WriteLine($_)
                  $Writer.Flush()
              }
              $Stream.Close()
              $Socket.Close()
              }

Last updated

Was this helpful?