Can only receive or send over TCP

I am having trouble writing a PowerShell script that can send and receive data over a TCP connection. It seems that this only allows me to do one or the other.

Below I am still. I want to listen and wait for the connection, and then after you install, get a string containing the IP address, do some fancy searches to find out the user has logged on to this computer, and then send the username. If I just send the data, it will work. If I get only data, it works. If I try to do both, only the reception will work. What am I doing wrong?

$port = 1234

do {
  $user = ""

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

  $client = $listener.AcceptTcpClient() # will block here until connection
  $stream = $client.GetStream();

  $reader = New-Object System.IO.StreamReader $stream
  $writer = New-Object System.IO.StreamWriter $stream

  $add = $reader.ReadLine()
  #$reader.close()

  write-host "Request from " $add

  if($add) {
    $user = & wmic /Node:$add ComputerSystem Get UserName
    write-host "User returned is " $user[2]
  }

  if($user[2] -eq "ERROR:") {
    $user[2] = "ErrNoUserW"
  } elseif(!$user[2]) {
    $user[2] = "ErrServerW"
  }

  $writer.Write($user[2])

  #$writer.close()
  $stream.close()
  $client.close()
  $listener.stop()
} while(1)
+4
source share
1 answer

, . , ?

0

Source: https://habr.com/ru/post/1598432/


All Articles