2

我的目标是向服务器应用程序发送和接收简单的字节数组(简单的 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
 # }

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

谢谢你。

4

2 回答 2

0

谢谢,最后我有以下代码:

# 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)'
于 2012-06-09T16:48:06.140 回答
0

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

于 2012-06-08T17:54:12.793 回答