powershell 通过TCP发送/接收字节数组

b4wnujal  于 2023-01-17  发布在  Shell
关注(0)|答案(2)|浏览(142)

我的目标是向/从服务器应用程序发送和接收简单的字节数组(简单的Java工具,对所有请求返回30字节的固定响应)。
我已经用以下代码完成了第一部分(通过TCP发送字节数组):

# Define port and target IP address 
  [int] $Port = 2222
  $IP = "172.16.0.51"
  $Address = [system.net.IPAddress]::Parse($IP) 

  # Create IP Endpoint 
  $End = New-Object System.Net.IPEndPoint $address, $port 

  # Create Socket 
  $Saddrf = [System.Net.Sockets.AddressFamily]::InterNetwork 
  $Stype = [System.Net.Sockets.SocketType]::Stream 
  $Ptype = [System.Net.Sockets.ProtocolType]::TCP
  $Sock = New-Object System.Net.Sockets.Socket $saddrf, $stype, $ptype 
  $Sock.TTL = 26 

  # Connect to socket 
  $sock.Connect($end)

  # Create byte array
  # TCP [Byte[]] $Message = 0xAA,0x55,0x00,0x12,0x00,0x00,0x00,0x7B,0x00,0x00,0x00,0x41,0x00,0x00,0x00,0x00,0xD6,0xDE,0xD5,0xA7,0x14,0x00
  [Byte[]] $Message = 0xAA,0x55,0x00,0x12,0x00,0x00,0x00,0x7B,0x00,0x00,0x00,0x41,0x00,0x00,0x00,0x00,0xD6,0xDE,0xD5,0xA7,0x14,0x00

 # for ($i=0; $i -le 1000; $i++)
 # {
  # Send the byte array 
  $Sent = $Sock.Send($Message)
  "{0} characters sent to: {1} " -f $Sent,$IP
  "Message is: $Message" 
  # End of Script
 # }

但是我无法找到/添加/创建能够在发送此类请求后立即接收响应的代码。有人能帮助我吗?
谢谢你。

vsdwdz23

vsdwdz231#

查看System.Net.Sockets.Socket class on MSDN的文档,该类有各种Receive方法可用于从流中读取数据。

bis0qfac

bis0qfac2#

谢谢,最后我有下面的代码:

# Getting responses  
    $script:compare = new-object System.Byte[] 40  
    $end = 0  
    do  
    {  
            # Receive response  
        Start-Sleep -m 30  
        $buffer = new-object System.Byte[] 40  
        $Received = $Sock.Receive($buffer)  
        if (@(Compare-Object $buffer $compare).length -ne 0)  
        {     
            Write-Host "TCP Message received:" $buffer  
            # Encode received response to ASCII  
            $Encode = new-object "System.Text.ASCIIEncoding"  
            $test = $Encode.GetString($buffer)  
            Add-Content -value "$(Time) $test" -Path tcp_response.log  
            $end = 1  
        }  
    } while ($end -eq 0)'

相关问题