我在编写可以通过TCP连接发送和接收数据的PowerShell脚本时遇到问题。它似乎只是让我做一个或另一个。
以下是我到目前为止的情况。我想监听并等待连接,然后一旦建立,接收包含IP地址的字符串,做一些奇特的查找以查看用户登录到该计算机,然后发回用户名。如果我只发送数据,它可以工作。如果我只收到数据,它就有效。如果我尝试两者都做,只有接收工作。我做错了什么?
$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)
答案 0 :(得分:0)
我认为只能在任何给定时间读取或写入流。您是否尝试关闭流然后重新打开它?