first commit
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Connects to a tcp-echo instance, prints the greeting, sends a message and prints the reply.
|
||||
.EXAMPLE
|
||||
.\test-echo.ps1 -Server sparkyxf.cz -Port 9098
|
||||
.\test-echo.ps1 -Server sparkyxf.cz -Port 9099 -Message "ping"
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true, Position = 0)]
|
||||
[string]$Server,
|
||||
|
||||
[Parameter(Mandatory = $true, Position = 1)]
|
||||
[ValidateRange(1, 65535)]
|
||||
[int]$Port,
|
||||
|
||||
[string]$Message = "hello",
|
||||
|
||||
[int]$TimeoutMs = 5000
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
function Read-Line {
|
||||
param([System.IO.StreamReader]$Reader)
|
||||
$line = $Reader.ReadLine()
|
||||
if ($null -eq $line) { throw "Connection closed by server." }
|
||||
return $line
|
||||
}
|
||||
|
||||
$client = New-Object System.Net.Sockets.TcpClient
|
||||
try {
|
||||
$client.ReceiveTimeout = $TimeoutMs
|
||||
$client.SendTimeout = $TimeoutMs
|
||||
|
||||
Write-Host "Connecting to ${Server}:${Port} ..." -ForegroundColor Cyan
|
||||
if (-not $client.ConnectAsync($Server, $Port).Wait($TimeoutMs)) {
|
||||
throw "Connect to ${Server}:${Port} timed out after ${TimeoutMs} ms."
|
||||
}
|
||||
|
||||
$stream = $client.GetStream()
|
||||
$reader = New-Object System.IO.StreamReader($stream, [System.Text.Encoding]::UTF8)
|
||||
$writer = New-Object System.IO.StreamWriter($stream, (New-Object System.Text.UTF8Encoding($false)))
|
||||
$writer.NewLine = "`n"
|
||||
$writer.AutoFlush = $true
|
||||
|
||||
Write-Host "<- $(Read-Line $reader)" -ForegroundColor Green # greeting: [instance] connected
|
||||
Write-Host "-> $Message"
|
||||
$writer.WriteLine($Message)
|
||||
Write-Host "<- $(Read-Line $reader)" -ForegroundColor Green # echo: [instance] <message>
|
||||
}
|
||||
finally {
|
||||
$client.Dispose()
|
||||
}
|
||||
Reference in New Issue
Block a user