# Chapter6: Socket Programming

## This section contain the following items:

* 1.TCP server/client  &#x20;

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jen-hsuan-hsieh.gitbook.io/powershell-programming-and-relative-experience/chapter6-socket-programming.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
