TCP 发件人
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)
# Write message to stream
$Message | % {
$Writer.WriteLine($_)
$Writer.Flush()
}
# Close connection and stream
$Stream.Close()
$Socket.Close()
}
}
发送消息:
Send-TCPMessage -Port 29800 -Endpoint 192.168.0.1 -message "My first TCP message !"
注意 :你的软件防火墙或你尝试通过的任何面向外部的防火墙可能会阻止 TCP 消息。确保你在上述命令中设置的 TCP 端口已打开,并且你已在同一端口上设置了侦听器。