我试图制作一个小的 TCP 客户端发送和接收脚本来将实际日期发送到工业相机。该设备预计 [date]<CR>
作为结束字符,并发送回 OK<CR>
或ER<CR>
消息。
我在这里找到了一个用于发送的基本脚本:https://riptutorial.com/powershell/example/18118/tcp-sender
我已经向其中添加了 StreamReader 函数,使用 Hercules SETUP Utility 进行测试,它会返回一条返回消息...如果结束字符是 <LF>
...但我需要<CR>
发送和接收也。 Communication manual, page 527.
Function Send-TCPMessage {
Param (
[Parameter(Mandatory=$true, Position=0)]
[ValidateNotNullOrEmpty()]
[string]
$EndPoint
,
[Parameter(Mandatory=$true, Position=1)]
[int]
$Port
,
[Parameter(Mandatory=$true, Position=2)]
[string]
$Message
)
Process {
# Setup connection
$IP = [System.Net.Dns]::GetHostAddresses($EndPoint)
$Address = [System.Net.IPAddress]::Parse($IP)
$Socket = New-Object System.Net.Sockets.TCPClient($Address,$Port)
# Setup stream wrtier
$Stream = $Socket.GetStream()
$Writer = New-Object System.IO.StreamWriter($Stream)
$Reader = New-Object System.IO.StreamReader($Stream)
# Write message to stream
$Message | % {
$Writer.WriteLine($_)
$Writer.Flush()
}
$Response = $Reader.ReadLine()
# Close connection and stream
$Stream.Close()
$Socket.Close()
return $Response
}
}
$retunMessage = Send-TCPMessage -Port 23 -Endpoint 127.0.0.1 -message "My first TCP message !"
Write-Host "Return Message = " $retunMessage
我尝试使用 Hercules SETUP Utility 进行测试,并通过 Google 查找修改结束字符的正确参数/设置。没有成功。有人可以帮助确定我应该设置哪些参数来将结束字符修改为 <CR>
?
最佳答案
用于书写
System.IO.StreamWriter
,设置其.NewLine
属性(在写入流之前):$Writer.NewLine = "`r" # CR
供阅读使用
System.IO.StreamReader
,您必须逐字符阅读:# Read a line terminated by a single CR $lineBuf = [System.Text.StringBuilder]::new(80) while (($codePoint = $Reader.Read()) -ne -1 -and $codePoint -ne 13) { $null = $lineBuf.Append([char] $codePoint) } $Response = $lineBuf.ToString()
注意:
通常,如果您的行仅以 CR 终止,则不需要额外的工作,因为行被定义为 (来自
System.IO.StreamReader
读者的.ReadLine()
文档;已添加重点):a sequence of characters followed by a carriage return (0x000d), a line feed (0x000a), a carriage return followed by a line feed, Environment.NewLine, or the end-of-stream marker.
- 换句话说:单独的 CR、单独的 LF 以及 CRLF 都被识别为换行符。
对于文件输入,使用
.ReadLine()
就足够了。但是,当与设备/间歇性流进行通信时,这意味着.ReadLine()
不会直到到达 EOF 或在 CR 之后至少有一个附加字符可以读取 CR 才返回,因为它必须检查该附加字符是否为LF,假设 CRLF 序列也是换行符。- 因此,为了防止在您的情况下读取一行可能无限期地阻塞,需要使用上面所示的逐字符读取方法。
关于Powershell - 如何设置 TCP 发送接收行结束字符? <CR> 与 <LF>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77060458/